. NET heap and stack 02, value type and reference type parameter transfer and memory allocation,. net type parameters

Source: Internet
Author: User

. NET heap and stack 02, value type and reference type parameter transfer and memory allocation,. net type parameters

In ". NET heap and stack 01, basic concepts, value-type memory allocation", I learned the basic concepts of "Heap" and "stack", and value-type memory allocation. We know that when a method is executed, the value type instance allocates memory on the stack, and the reference type instance allocates memory on the heap. When the method execution is complete, instances on the "stack" are automatically released by the operating system, and instances on the "stack" are automatically released.. NET Framework. This article focuses on the transfer of value type and reference type parameters and memory allocation.

 

It mainly includes:
■ Pass value type parameters
■ Transfer a value type parameter that may easily cause "stack overflow" and add the keyword ref before the value type parameter
■ Passing reference type parameters
■ Pass the reference type parameter and add the keyword ref before the reference type parameter

 

Pass value type parameters

class Class1     {          public void Go()          {              int x = 5;              AddFive(x);               Console.WriteLine(x.ToString());                        }           public int AddFive(int pValue)          {              pValue += 5;              return pValue;          }     }

 

The general process is as follows:

1. value type variable x is placed on the "stack.

 

2. Run the AddFive () method. The Value Type Variable pValue is put on the "stack" and the value of x is assigned to pValue. The value of pValue is changed to 5.

 

3. continue to run the AddFive () method. The value of pValue is changed to 10.

 

4. After the AddFive () method is executed, the pValue memory is released, the "stack" pointer returns to x, and the thread returns to the Go () method.

 

Output result: 5


As mentioned above, when passing the value type parameter x, x is actually copied to pValue in one byte.

 

Pass a value type parameter that may easily cause "stack overflow", and add the keyword ref before the value type parameter

public struct MyStruct           {               long a, b, c, d, e, f, g, h, i, j, k, l, m;           }          public void Go()          {             MyStruct x = new MyStruct();             DoSomething(x);                        }             public void DoSomething(MyStruct pValue)           {                    // DO SOMETHING HERE....           }

Assuming that the above value type struct is large enough, and x and pValue will be allocated to the "stack", this may cause "stack overflow ".

 

How can we avoid it?
-- The solution is to let DoSomething pass a ref type parameter. Write as follows:

public struct MyStruct           {               long a, b, c, d, e, f, g, h, i, j, k, l, m;           }          public void Go()          {             MyStruct x = new MyStruct();             x.a = 5;             DoSomething(ref x);              Console.WriteLine(x.a.ToString());                         }           public void DoSomething(ref MyStruct pValue)          {                   pValue.a = 12345;          }

 

After using ref, execute DoSomething (ref x) to assign the address of x to pValue, that is, pValue and x point to the same reference address. When the value of pValue is changed, the change is also reflected in x.

 

Output result: 12345

 

To avoid "stack overflow" caused by "large" value type parameter transfer, you can add the ref keyword before the value type. Therefore, when the value type parameter x is passed, in fact, the stack address of x is copied to pValue, and x and pValue point to the same stack address.

 

Pass reference type parameters

The principle of passing a reference type parameter is the same as adding the ref keyword before the passed value type parameter.

public class MyInt           {               public int MyValue;           }          public void Go()          {             MyInt x = new MyInt();             x.MyValue = 2;              DoSomething(x);              Console.WriteLine(x.MyValue.ToString());                        }            public void DoSomething(MyInt pValue)           {               pValue.MyValue = 12345;           }

Output result: 12345

 

The above general process is as follows:
1. Create an instance of the MyInt type on the managed Stack
2. Create a MyInt variable x on the stack to point to the instance on the stack.
3. Assign the public field MyValue on the hosting stack to 2.
4. Use the DoSomething (x) method to assign the reference address of x to pValue, that is, pValue and x point to the same reference address.
5. Changing the value of pValue will also be reflected on x.

 

As mentioned above, when the reference type parameter x is passed, the reference address of x pointing to the managed heap instance is actually copied to pValue, and the x and pValue point to the same managed heap instance address.

 

Pass the reference type parameter, and add the keyword ref before the reference type parameter

public class Thing           {           }            public class Animal:Thing           {               public int Weight;           }            public class Vegetable:Thing           {               public int Length;           }          public void Go()          {             Thing x = new Animal();                        Switcharoo(ref x);               Console.WriteLine(                "x is Animal    :   "                + (x is Animal).ToString());               Console.WriteLine(                  "x is Vegetable :   "                  + (x is Vegetable).ToString());                        }            public void Switcharoo(ref Thing pValue)           {               pValue = new Vegetable();           }

Output result:
X is Animal: False
X is Vegetable: True

 

The above general process is as follows:
1. Create an Animal object instance on the managed stack.
2. Create a Thing-Type x variable on the stack to point to the reference address of the Animal instance.
3. Assign the address of x to pValue through the Switcharoo (ref x) method. So far, pValue and x point to the same stack memory address, changes made by either party are reflected by the other party.

4. Create a Vegetable object instance on the managed stack within Switcharoo (ref Thing pValue.
5. pValue points to the Vegetable instance, which means that x points to the Vegetable instance.

 

Above, when the keyword ref is added before the reference type parameter, the stack address of x is copied to pValue, And the stack addresses of x and pValue point to the same stack address.

 

References:
C # Heap (ing) Vs Stack (ing) in. NET: Part II
NET (version 2nd), Author: Wang Tao.

 

". NET heap and stack" series include:

. NET heap and stack 01, basic concepts, value type memory allocation. NET heap and stack 02, value type and reference type parameter transfer and memory allocation. NET heap and stack 03, reference type object copy and Memory Allocation
NET Method in what form of storage, such as value type storage stack, reference type storage stack, where does the method exist?

The process memory space is divided into several segments, and the. net method is put in the code segment. The memory value in this segment cannot be changed.
"Value type storage stack, reference type storage stack" are all in the Data Segment

16. In NET, a page object is an instance of the () class.

System. Web. UI. Page

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.