In C #, value types and reference types are essentially homologous, so not only can you convert between value types and reference types, but you can also convert between value types and reference types. , but the different types of memory used by the two make their conversions more complex.
1. Packing:
In C #, it is common to convert a value type to a reference type called boxing.
The process of boxing a value type into a reference type in C # is as follows:
- Creates a new object instance in the managed heap and allocates the appropriate memory.
- Copy the value type variable value into the object instance.
- Presses the object instance address onto the stack and points to a reference type.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceconsoleapplication1{classProgram {Static voidMain (string[] args) { intMM = -;//defining value type variables Objectnn = mm;//Boxing a value-type variable to a reference type rollupConsole.WriteLine ("The value is {0} and the boxed object is {1}", nn,mm); MM= -;//Change ValueConsole.WriteLine ("The value is {0} and the boxed object is {1}", MM, nn); Console.readkey (); } }}
The results of the operation are as follows:
2. Unpacking:
In C #, it is common to convert a reference type to a value type called a unboxing. The process of unpacking a reference type into a value type in C # is as follows:
- Checks whether an instance of the object is a boxed value of a given value type.
- If yes, the value is copied from the instance.
- Assigns a value to a value type variable.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceconsoleapplication1{classProgram {Static voidMain (string[] args) { intMM = -; Objectnn =mm; Console.WriteLine ("Boxed: value {0}, boxed object {1}", MM, nn); intZZ = (int) nn;//Unboxing = UnpackingConsole.WriteLine ("Unpacking: The Boxed object is {0} and the value is: {1}", nn, ZZ); Console.readkey (); } }}
C # box and unboxing