ref modifier

To pass by reference we use the ref parameter modifier.

We add the ref modifier in front of the parameter.


using System;

class Program
{
    static void change(ref int i)
    {
        i = i + 1;
        Console.WriteLine("in change method:" + i);
    }


    static void Main(string[] args)
    {
        int i = 2;

        change(ref i);

        Console.WriteLine("in main method:" + i);
    }
}

The output:


in change method:3
in main method:3

The ref keyword is required in the method declaration as well as the method call.

From the output we can see that the int value in the main method is changed by the method change since the pointer to the int value is passed into the change method.

We can use the ref parameter modifier to exchange value of two parameters.


using System;

class Program
{
    static void swap(ref int a, ref int b)
    {
        int temp = a;
        a = b;
        b = temp;

    }


    static void Main(string[] args)
    {

        int i = 5;
        int j = 6;

        Console.WriteLine(i);
        Console.WriteLine(j);

        swap(ref i, ref j);


        Console.WriteLine(i);
        Console.WriteLine(j);
    }
}

The output:


5
6
6
5

We can use ref modifier for reference type value as well.


using System;
class Rectangle
{
    public int Width = 5;
    public int Height = 5;

}

class Program
{
    static void change(ref Rectangle r)
    {
        r = null;
    }

    static void Main(string[] args)
    {


        Rectangle r = new Rectangle();
        Console.WriteLine(r.Width);
        change(ref r);
        Console.WriteLine(r == null);
    }
}

The output:


5
True

If we use the ref modifier in front of a reference type what we get in the method is the address of the reference or the reference of the reference.

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.