开发者

Object Behaviour

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());
    }


When you call method2(Class1 c1) you are passing a copy of the reference to the object, not the object itself (or the reference to it). When you set c1 = null you are setting the copy of the reference to be null, not the object.

You can get the behaviour you expect by changing your method signature to this:

method2(ref Class1 c1)


In C#, references are passed by value. That is, method2 receives a copy of the value of the reference to c1.

In method2 setting c1 = null affects the local copy of the reference only.

See this article for more info


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).


Hopefully a simple edit of your code can show you why:

public class Class1
{
    public int i;
    public Class1()
    {
        i = 10;
    }    

    public string method1()
    {
        return "str";
    }
}

public class Class2
{
    public void method2(Class1 myLocalReference)
    {
        myLocalReference.i = 100;
        myLocalReference = null;
    }
}

void main()
{
    Class1 c1 = new Class1();
    Class2 c2 = new Class2();
    c2.method2(c1);
    Response.Write(c1.method1());
    Response.Write(c1.i.ToString());
}

I think that shows clearly that the reference used in Class2.method2 isn't the same as that used in main. c1 is declared in main, when used as a parameter in the method call c2.method2(c1); the reference to your Class1 instances is copied into a new local value called myLocalReference. You then set myLocalReference = null; and within method2 you would find that Response.Write(myLocalReference.method1()); or Response.Write(myLocalReference.i.ToString()); would fail appropriately. When method2 exits the local reference myLocalReference goes out of scope and you return to main where the c1 reference exists and is unchanged so the subsequent Response.Write methods succeed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜