The existence of both reference types (classes) and value types (structs, enums and primitive types) is one of those things that makes object-oriented programming more efficient.
The key distinction between the two types is where they stored in memory:
Value types > on the stack
Classes > on the heap and are referred to by one or more stack-based references.
One of C#’s notable advantages over Java is that C# makes this process transparent.
The processes called boxing and unboxing wrap and unwrap a value type in an object.
Thus, the INT primitive type can be boxed into an object of the class Int32, a bool is boxed into a Boolean, etc.
Boxing and unboxing happen transparently between a variable declared as the value type and its equivalent class type.
Thus, you can write code like the following:
- bool b = true;
- Boolean referenceType1 = b; //Boxing
- bool valueType2 = referenceType1; //Unboxing
You should know:
There is one value type for which the benefits of boxing and unboxing become apparent immediately: the string.
..