Pages

Tuesday, October 12, 2010

Difference between ref & out

The out and the ref  parameters are very useful when your method needs to return more than one values.
The out Parameter
1. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.
2. Variables passed as an out arguments need not be initialized prior to being passed.
class Example
{
    static void Method(out int i)
    {
        i = 90;
    }
    static void Main()
    {
        int k;
        Method(out k);
        // k is now 90
    }
}
3. The calling method is required to assign a value before the method returns.
class Example
{
    static void Method(out int i)
    {
        i = 90;
    }
    static void Main()
    {
        int k;
        Method(out k);  // k is now 90       
    }
}
The ref parameter
1. ref requires that the variable be initialized before being passed.
class Example
{
    static void Method(ref int i)
    {
        i += 30;
    }
    static void Main()
    {
        int k=3;
        Method(ref k);  // k is now 33       
    }
}

Note:
Methods cannot be overloaded if one method takes a ref argument and the other takes an out argument. These two methods, for example, are identical in terms of compilation, so this code will not compile:
class Example
{
    // compiler error CS0663: "cannot define overloaded
    // methods that differ only on ref and out"
    public void Method(out int i) {  }
    public void Method(ref int i) {  }
}
Overloading can be done, however, if one method takes a ref or out argument and the other uses neither, like this:
class Example
{
    public void Method(int i) {  }
    public void Method(out int i) {  }
}

No comments:

Post a Comment