Tuesday, July 24, 2012

Ref Keyword in C#

The ref keyword causes arguments to be passed by reference. The effect is that any changes to the parameter in the method will be reflected in that variable when control passes back to the calling method.

class RefExample
{
static void Method(ref int i)
{
i = 44;
}
static void Main()
{
int val = 0;
Method(ref val);
// val is now 44
}
}

An argument passed to a ref parameter must first be initialized. This differs from out, whose arguments do not have to be explicitly initialized before they are passed. For more information, see out.

Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a ref argument and the other takes an out argument. The following code, for example, will not compile:
class CS0663_Example
{
// Compiler error CS0663: "Cannot define overloaded
// methods that differ only on ref and out."
public void SampleMethod(out int i) { }
public void SampleMethod(ref int i) { }
}
Overloading can be done, however, if one method takes a ref or out argument and the other uses neither as in the following example:
class RefOverloadExample
{
public void SampleMethod(int i) { }
public void SampleMethod(ref int i) { }
}
Properties are not variables. They are actually methods, and therefore cannot be passed as ref parameters.
For information about how to pass arrays, see Passing Arrays Using ref and out (C# Programming Guide).(MSDN LINK)
class RefExample2
{
static void Method(ref string s)
{
s = "changed";
}
static void Main()
{
string str = "original";
Method(ref str);
Console.WriteLine(str);
}
}
// Output: changed

No comments:

Post a Comment