C # value type and reference type

Source: Internet
Author: User

Different Storage:

The value type is stored in the stack, and the reference type is stored in the managed stack.

Value Type example:

I = 20;

J = I;

The above statement stores 20 values in two places of memory;

Example of reference type:

    class Vector    {        public long value { get; set; }    }    class Program    {         static void Main(string[] args)        {            Vector x, y;            x = new Vector();            x.value = 30;            y = x;            Console.WriteLine(y.value);            y.value = 50;            Console.WriteLine(x.value);            Console.ReadKey();        }            }
View code

The above code, X value assignment, Y value also changes, Y value assignment, X value also changes, the result is 30 and 50

Different reference types: String

String S1, S2;
S1 = "123 ";
S2 = S1;
Console. writeline ("S1:" + S1 );
Console. writeline ("S2:" + S2 );
S1 = "456 ";
Console. writeline ("S1:" + S1 );
Console. writeline ("S2:" + S2 );
Console. readkey ();

Result: S1: 123

S2. 123

S1. 456

S2. 123

The result shows that changing the S1 value has no effect on S2 because the string cannot be changed. modifying a string creates a new String object.

The other string will not change.

Summary: In C #, the basic data types such as bool and long are both value types. If you declare a bool variable and assign it to the value of another bool variable,

There will be two bool values in the memory. If you change the first bool value in the future, the value of the second bool variable will not change.

If it is defined as a value type, it should be declared as a structure.

 

C # value type and reference type

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.