Make a reference to another string in C#

前端 未结 5 892
夕颜
夕颜 2021-01-19 22:25

As far as I know a string in C# is a reference type.

So in the following code \'a\' should be equal to \"Hi\", but it still keeps its value which is \"Hello\". Why?<

5条回答
  •  醉酒成梦
    2021-01-19 22:31

    The concept of a reference type is the most confusing thing amongst OOP programmers.

    Run the below code, and you will be surprised to see the answer:

    Create a simple Book class with a property called Name and write the below code in the Main method of the application.

    Book a = new Book() {Name = "book a"};
    Book b = new Book() {Name = "book b"};
    
    Book c = a; //line 3
    
    Book a = b; //Line 4
    
    Console.WriteLine(c.Name);
    

    And as no doubt you will expect the answer to be "book b" because of line 4. You think that as c is a and after that a became b which will also make c equals b.

    Which is not the case!

    Read the balloon anology at Ballon analogy for Reference type.

提交回复
热议问题