In the previous post, I introduced the basics of value types. In today's post, I continue to introduce you to reference types. What is a reference type? What types are there? Is it possible to convert from a reference type to a value type?
As we know the value type will store the value of a variable directly, and that value is stored on the stack. Unlike the value type, the reference type does not store the value directly, but it does contain a pointer to the memory area where the value is stored. The value of the reference type is stored on the heap.
To understand better, we can consider the following illustrative example:
In the above example, I create a variable name with a data type string and do not initialize it. I then assign a value to the variable name. The name variable will store in allocated memory "M100" and the M100 will point to the actual value I assigned to the variable name = “Victor”.
Could I convert a value from Reference type to Value type??
Definitely yes, and that conversion technique in the coding world they call "boxing and unboxing".
Boxing is a conversion from a value type to a reference type. Boxing is also known as implicit conversion. During conversion, the CLR will convert the value type to System. Object and store it on the Heap.
Let check this example:
In the above example, the CLR will create a variable int i = 10 and store it on the stack. Then will create a variable "o" on the heap and copy its value to the corresponding allocated memory for the object "o".
Unboxing will convert from a reference type to a value type. Unboxing is also understood as converting the data type explicitly.
In the first two lines, the CLR will convert from value type to reference type. The next line will perform the conversion from a reference type to a value type, which also includes checking if object o is holding a value of type int?
Let see this example:
Here is the result:
The reason, during unboxing, the CLR will perform checks to make sure the boxed object is of the correct type given.
Thus, we have understood the basic concept of value types and reference types, as well as understand their conversion using boxing and unboxing techniques.
Related Posts:





0 nhận xét:
Đăng nhận xét