i have a class
class ABC
{
public int a = 2;
public void valueA(ABC objabc)
{
a = 5;
objabc = new ABC();
objabc.a = 11;
}
}
then i write main as
static void Main(string[] args)
{
ABC objabc = new ABC();
objabc.a = 15;
objabc.valueA(objabc);
Console.WriteLine(objabc.a);
}
When i execute this i found 5 in output.so my question is that why a = 5??why it is not 2, 11 or 15??
You are calling the
valueAmethod on the objectobjabc. Inside the method the memberaofthisis set to 5. You can see the code as equivalent to:So you are setting the member of the object on which you called the method to 5. This object being
objabcfrommain, so the final value is 5. The fact that you are assigning it a new object reference afterwards makes no difference, because you are not passing it by reference so changes are not visible outside.The result would be different (i.e. 11) if your code was this:
In this case the parameter would be passed by reference, so the assignment
objabc = new ABC();would be visible to the calling code (i.e. inMain).