Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# object pass by reference or pass by value

The output of the following code surprised me. I think "a" should hold a reference to the newly created object. Can someone explain why the result is not 2?

class Program
{
    static void Main(string[] args)
    {
        aclass a = new aclass();
        Process(a);
        Console.WriteLine(a.number);

        Console.ReadLine();
    }

    static void Process(aclass a)
    {
        aclass temp = new aclass();
        temp.number++;
        //Console.WriteLine(temp.number);

        a = temp;
        a.number++;
        //Console.WriteLine(a.number);
    }

}

class aclass
{
    public int number = 0;
}

Edit: This is an interview question. I just realized I had misunderstood the concept for long time. The argument a is different to the original a although they reference to the same address.

like image 822
mortdale Avatar asked Dec 26 '22 19:12

mortdale


1 Answers

You're not changing the actual original reference you're just changing the reference held in the parameter which subtly isn't the same, the changes aren't persisted back to the caller. You can change this behaviour by using out or ref.

In this case specifically you'd want to use ref as you're also passing a reference in.

Try:

class Program
{
    static void Main(string[] args)
    {
        aclass a = new aclass();
        Process(ref a);
        Console.WriteLine(a.number);

        Console.ReadLine();
    }

    static void Process(ref aclass a)
    {
        aclass temp = new aclass();
        temp.number++;
        //Console.WriteLine(temp.number);

        a = temp;
        a.number++;
        //Console.WriteLine(a.number);
    }

}

Remember you're assigning a whole new reference with a = temp. If you just wanted to update the existing class you originally passed in then you could do:

a.number = temp.number;
a.number++;

This would negate the need for ref.

You can read more on MSDN:

Passing Reference Type Parameters

ref Keyword

out Keyword

like image 187
Lloyd Avatar answered Dec 28 '22 11:12

Lloyd