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: