Difference between ref and out parameters




Difference between ref and out parameters

Ref:
The ref keyword is used for passing parameter by reference
Need to be initialized before passing

Out:
The out paramter is used when method want to return multiple values
It is not mandatory to initialize paramter before passing

Ref and out in method overloading

Both ref and out cannot be used in method overloading simultaneously. However, ref and out are treated differently at run-time but they are treated same at compile time. Hence methods cannot be overloaded when one method takes a ref parameter and other method takes an out parameter. The following two methods are identical in terms of compilation.




class MyClass
{
public void Test(out int a) // compiler error “cannot define overloaded”
{
// method that differ only on ref and out”
}
public void Test(ref int a)
{
// method that differ only on ref and out”
}
}

However, method overloading can be done, if one method takes a ref or out argument and the other method takes simple argument. The following example is perfectly valid to be overloaded.

class MyClass
{
public void Test(int a)
{

}
public void Test(out int a)
{
// method differ in signature.
}
}




It's only fair to share...Email this to someoneShare on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *