Friday, 27 May 2016

out and ref keyword

out and ref parameters

In a class instance you need not worry about getting value in a separate variable because the type is already being passed to a reference and it will maintain the changes when it returns.
Problem occurs when you need the value to be returned in the value type.  So that time out and ref parameter is help to get as value type.
Out:
Out keyword defines an out type parameters.
Out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable
myMethod(out int iVal1)

Using the out parameter

using System;

class Program
{
    public static void returnData(out int val1,out int val2)
    {
        val1 = 2;
        val2 = 5;
    }

    static void Main()
    {
        int iv1, iv2;

        returnData(out iv1,out iv2);

        Console.WriteLine(iv1);
        Console.WriteLine(iv2);
    }
}

Ref keyword defines a ref type parameter.
You can use the ref parameter as a method in put parameter and an output parameter. Any changes made to the parameter will be reflected in the variable.
myMethod(ref int iVal1)

Using the ref parameter


using System;

class Program
{
    public static void returnData(ref int val1, ref int val2)
    {
        val1 += 2;
        val2 += 5;
    }

    static void Main()
    {
        int iv1, iv2;

        iv1 = 2;
        iv2 = 2;

        Console.WriteLine(iv1);
        Console.WriteLine(iv2);

        returnData(ref iv1, ref iv2);

        Console.WriteLine(iv1);
        Console.WriteLine(iv2);
    }
}

you can also visit:  www.mybook-lang.com

No comments:

Post a Comment