Wednesday, April 6, 2016

Ref and out parameter in c#



Ref parameter: -The ref keyword will pass the parameter as a reference, if we want to pass a variable as a ref then we need to initialize it before pass it as reference parameter to method .The main features of the ref parameter is that when the value of the parameter is changed in called method it is also reflected in calling method.

Example:

class class1
{
    static void Main()
    {
        int i;
        i = 5;
        Ref(ref i);
        Console.WriteLine(i);
    }
    public static void Ref(ref int val)
    {
        val += 10;
    }
}

Output: 15

Out parameter - The out keyword will pass the parameter as a reference, if we want to pass a variable as a out then we need to initialize it before pass it as reference parameter to method .Out parameter is initialized in called method before it return the value to calling method.
class class1
{
    static void Main()
    {
        int i, j;
        Out(out i, out j);
        Console.WriteLine(i);
        Console.WriteLine(j);
    }
    public static int Out(out int val, out int val1)
    {
        val = 15;
        val1 = 10;
        return 0;
    }
}

Output : 15,10

No comments:

Post a Comment