Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

.net - Reference type in C#

Consider this code:

public class Program
{
    private static void Main(string[] args)
    {
        var person1 = new Person { Name = "Test" };
        Console.WriteLine(person1.Name);

        Person person2 = person1;
        person2.Name = "Shahrooz";
        Console.WriteLine(person1.Name); //Output: Shahrooz
        person2 = null;
        Console.WriteLine(person1.Name); //Output: Shahrooz
    }
}

public class Person
{
    public string Name { get; set; }
}

Obviously, when assigning person1 to person2 and the Name property of person2 is changed, the Name of person1 will also be changed. person1 and person2 have the same reference.

Why is it that when person2 = null, the person1 variable will not be null either?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Both person and person2 are references, to the same object. But these are different references. So when you are running

person2 = null;

you are changing only reference person2, leaving reference person and the corresponding object unchanged.

I guess the best way to explain this is with a simplified illustration. Here is how the situation looked like before person2 = null:

Before null assignment

And here is the picture after the null assignment:

Enter image description here

As you can see, on the second picture person2 references nothing (or null, strictly speaking, since reference nothing and reference to null are different conditions, see comment by Rune FS), while person still references an existing object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...