. NET heap and Stack 02, value type and reference type parameter passing, and memory allocation

Source: Internet
Author: User

In the. NET heap and Stack 01, basic concepts, value type memory allocation, the basic concepts of "heap" and "stack", and the memory allocation of value types. 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, and when the method executes, the instance on the stack is automatically freed by the operating system, and the instance on the heap is reclaimed by the. NET Framework's GC. The focus of this article is on the delivery of value types and reference type parameters, as well as memory allocations.

Mainly include:
Passing Value type parameters
Pass a value type parameter that is prone to "stack Overflow", plus the keyword ref before the value type parameter
Passing reference type parameters
Pass a reference type parameter and precede the reference type parameter with the keyword ref

Passing Value type parameters

class Class1     {          publicvoid  Go ()          {              int5;              Addfive (x);               Console.WriteLine (X.tostring ());                        }             Public int Addfive (int  pValue)          {              5;               return pValue;          }     }

The approximate process is as follows:

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

2. Start the execution of the Addfive () method, the value type variable pvalue is placed on the "stack", and the value of x is assigned to the value of Pvalue,pvalue to become 5.

3, continue to execute the addfive () method, the value of Pvalue becomes 10.

4, after executing the addfive () method, releasing the Pvalue memory, the "stack" pointer back to x, the thread back to the Go () method.

Output results: 5


Above, when passing the value type parameter x, it is actually to copy the x byte one byte to the pvalue.

Pass a value type parameter that is prone to "stack Overflow", plus 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 ()          {             new  mystruct ();             DoSomething (x);                        }               Public void dosomething (mystruct pValue)           {                    // do SOMETHINGhere ...           }

Assuming that the above value type struct is large enough, and that X and Pvalue are assigned to the "stack", this can result in a "stack Overflow".

How to avoid it?
--The workaround is to have dosomething pass a ref type parameter. Write this:

 Public structMyStruct {LongA, B, C, D, E, F, G, H, I, J, K, L, M; }           Public voidGo () {mystruct x=NewMyStruct (); X.A=5; DoSomething (refx);                         Console.WriteLine (X.a.tostring ()); }            Public voidDoSomething (refmystruct PValue) {Pvalue.a=12345; }

With ref, the execution of dosomething (ref X) assigns the address of X to Pvalue, where pvalue and X point to the same reference address. When you change the value of the pvalue, the change is reflected in the X.

Output results: 12345

Above, in order to avoid the "large" value type parameter passed the "stack Overflow", you can precede the value type with the REF keyword, so, when the value type parameter x is passed, it is actually the stack address of the x itself is copied to pvalue,x and Pvalue point to the same stack address.

Passing reference type parameters

Passing a reference type parameter is the same as adding the REF keyword before the value type argument passed.

 Public classMyInt { Public intmyvalue; }           Public voidGo () {MyInt x=NewMyInt (); X.myvalue=2;              DoSomething (x);                        Console.WriteLine (X.myvalue.tostring ()); }             Public voiddosomething (MyInt pValue) {Pvalue.myvalue=12345; }

Output results: 12345

This is the general process:
1. Create an instance of the Myint type on the managed heap
2. Create a variable of type myint on the stack x point to the instance on the heap
3. Assign a value of 2 to the public field myvalue on the managed heap
4, by DoSomething (x) method, the reference address of X is assigned to Pvalue, that is pvalue and X point to the same reference address
5, change the value of Pvalue, will also be reflected on the X

Above, when the reference type parameter x is passed, it is actually a copy of the reference address of X pointing to the managed heap instance to pvalue,x and pvalue to the same managed heap instance address.

Pass a reference type parameter and precede the reference type parameter with the keyword ref

 Public classThing {} Public classanimal:thing { Public intWeight; }             Public classvegetable:thing { Public intLength; }           Public voidGo () {Thing x=NewAnimal (); Switcharoo (refx); Console.WriteLine ("x is Animal:"+ (x isAnimal).               ToString ()); Console.WriteLine ("x is vegetable:"+ (x isvegetable).                        ToString ()); }             Public voidSwitcharoo (refThing PValue) {PValue=NewVegetable (); }

Output Result:
X is Animal:false
X is Vegetable:true

This is the general process:
1. Create an instance of the animal object on the managed heap.
2. Create an X variable of type thing on the stack to point to the reference address of the animal instance.
3, through the Switcharoo (ref x) method to assign the address of the x itself to pvalue, so that pvalue and X point to the same stack memory address, either side of the change will be reflected on the other side.

4. Within Switcharoo (ref Thing PValue), create a Vegetable object instance on the managed heap.
5, Pvalue point to vegetable instance, it is equivalent to X point to vegetable instance.

Above, when the reference type parameter is preceded by the keyword ref, and then passed, is to copy the stack address of the x itself to Pvalue,x and Pvalue point to the same stack address.

Resources:
C # Heap (ing) Vs Stack (ing) in. Net:part II
You must know. NET (2nd edition), author Wang Tao.

". NET Heap and Stack "series includes:

. NET heap and Stack 01, basic concept, value type memory allocation. NET heap and Stack 02, value type and reference type parameter passing, and memory allocation

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.