Understand C # reference type,

Source: Internet
Author: User

Understand C # reference type,

A Bug occurred in the project due to insufficient understanding of the reference type.

First, sort out C # basics: The reference type value assignment assigns the object pointer, while the value type value assignment is the copy, which is one of the differences between the reference type and the value type.

Code:

 1  class Program 2     { 3         static void Main(string[] args) 4         { 5             var obj = MyClassA.PropertyA; 6             Console.WriteLine(string.Join(",", MyClassA.PropertyA.Foo)); 7             obj.Foo.RemoveAll(m => m == "e"); 8             Console.WriteLine(string.Join(",",MyClassA.PropertyA.Foo)); 9 10             Console.WriteLine(string.Join(",",MyClassA.PropertyA.Bar));11             obj.Bar = obj.Bar.Where(m => m > 2).ToList();12             Console.WriteLine(string.Join(",", MyClassA.PropertyA.Bar));13 14             obj.Foo = new List<string> {"x", "y", "z"};15             Console.WriteLine(string.Join(",", MyClassA.PropertyA.Foo));16 17             Console.Read();18         }19     }20     class MyClassA21     {22         static MyClassA()23         {24             PropertyA=new MyClassB();25             PropertyA.Foo = new List<string> { "a", "b", "c", "d","e"};26             PropertyA.Bar = new List<int> {1, 2, 3, 4, 5};27         }28         public static MyClassB PropertyA { get; private set; }29     }30 31     class MyClassB32     {33         public List<string> Foo { get; set; }34         public List<int> Bar { get; set; }35     }

It is hard to understand: I clearly operate on the internal members of obj. Why is the value of MyClassA. PropertyA changed?

Because, when MyClassA. PropertyA is assigned to obj, obj points to MyClassA (reference type). Therefore, as long as the object is operated on, it is actually an internal Member of MyCalssA.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.