Reputation: 392
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.
Upvotes: 4
Views: 801
Reputation: 2910
It is basically the difference between
In the example, Process(a) - 'a' which is a reference type, is passed to the method without the ref parameter. In such a case, a copy of the reference, which points to a, is passed to the method.
Allocating a new portion of memory by using the new operator inside the Process method makes the variable 'a' reference a new object of aclass. Thus, any changes after that will not affect the original object 'a'.
Refer MSDN : http://msdn.microsoft.com/en-us/library/s6938f28.aspx
Upvotes: 0
Reputation: 27659
This line aclass a = new aclass();
creates a variable (Space where we can store data) in memory. Consider that its address in memory is *(0x12DF)
and the value
which is stored at that location is object a
This line Process(a)
passes the VALUE
of object a
NOT THE ADDRESS to function Process
, so anything happens in Process()
has nothing to do with the contents
of location *(0x12DF)
, so the contents of location *(0x12DF)
will remain the same as it was before calling Process()
.
CONTENTS OF *(0x12DF)
= a
I hope its helpful instead of creating more confusion!!
Upvotes: 0
Reputation: 29668
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
Upvotes: 10