Difference between boxing and unboxing in c#
In C#, "boxing" is the process of converting a value type to a reference type, while "unboxing" is the process of converting a reference type back to a value type.
Boxing occurs when a value type is assigned to a variable of type `object` or an interface type that the value type implements. When this happens, a new object is created on the heap to store the value type, and a reference to this object is assigned to the variable.
Example of boxing:
int num = 42;
object boxedNum = num; // boxing occurs here
Unboxing, on the other hand, is the process of extracting the value type from the object and assigning it to a value type variable. This is done using a type cast operator.
Example of unboxing:
object boxedNum = 42;
int num = (int)boxedNum; // unboxing occurs here
Boxing and unboxing can have a performance impact, especially when done in a loop or in performance-critical code. This is because boxing and unboxing involve creating new objects on the heap and performing type checks at runtime. To avoid boxing and unboxing, it is generally recommended to use generics and value types wherever possible.
No comments:
Post a Comment
If you have any query kindly let me know.