C # value type and reference type,

Source: Internet
Author: User

C # value type and reference type,

Reference Type: always allocated from managed heap

Class, interface, delegate

System. Object, System. String, List, Decoder, etc.

Value Type: generally distributed on the thread stack (Exceptions: Elements in the array, value type fields in the reference type, local variables in the iterator block, and local variables in the closure)

Struct

System. Int32, System. Float, System. Boolean, System. Enum

 

Let's take a look at the class and struct:

 1 namespace RefValTest 2 { 3     class TestRef 4     { 5         public int a; 6         public int b; 7  8         public TestRef(int a, int b) 9         {10             this.a = a;11             this.b = b;12         }13     }14 15     struct TestVal16     {17         public int a;18         public int b;19 20         public TestVal(int a, int b)21         {22             this.a = a;23             this.b = b;24         }25     }26 27     class Program28     {29         static void Main(string[] args)30         {31             TestRef tr = new TestRef(1, 2);32             TestRef tr2 = tr;33             tr2.a = 3;34             System.Console.WriteLine(tr.a); // 335 36             TestVal tv = new TestVal(1, 2);37             TestVal tv2 = tv;38             tv2.a = 3;39             System.Console.WriteLine(tv.a); // 140 41             System.Console.ReadLine();42         }43     }44 }

 

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.