Wednesday 16 March 2011

Using ref and out keywords in c#

what is the use of ref and out keyword in C#?

When we pass value of value type or implicit data type to a method we actually pass
a copy of data. so any changes or modification done in the method in data is not reflected
back.

Consider an example:

class refoutsample
{
    public static void Main(string args[])
    {
        int a =3;
        add(a);
        Console.WriteLine("Value of a is" + a);
    }
    public static void add(int i)
    {
        i++;
    }
}

Output of this program is "value of a is 3" though the value is incremented by 1 in the method.
so to avoid this ref or out keyword is used.

P{rogram using ref keyword:

class refoutsample
{
    public static void Main(string args[])
    {
        int a =3;
        add(ref a);
        Console.WriteLine("Value of a is" + a);
    }
    public static void add(ref int i)
    {
        i++;
    }
}

now the output is 4.

Diffrence between ref and out keyword?

In case of ref, value must be initialized before passing it to method whereas in case of out keyword its not necessary.


    

No comments:

Post a Comment