Can anyone explain the behaviour of the below code. The output of the below code is string “str” and i’s value is 100.
But why is it so? After setting object c1 = null, why isn’t it null?
public class Class1
{
public int i;
public Class1()
{
i = 10;
}
public string method1()
{
return "str";
}
}
public class Class2
{
public void method2(Class1 c1)
{
c1.i = 100;
c1 = null;
}
}
void main()
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
c2.method2(c1);
Response.Write(c1.method1());
Response.Write(c1.i.ToString());
}
This is a pass-by-reference/pass-by-value thing. Javaranch Camp site stories: Pass By Value Please explains it very well. I know the above link is for Java, and this is a C# question, but the same thing happens (unless the “ref” keyword is used).