Variable Conversion in C#

In this article we’ll be looking at two of the variable conversion methods in C#.

Reference Conversion

A reference conversion is simply converting a variable from one reference type to another. Reference conversions can be either implicit or explicit. This conversion never changes the referential identity of the object which is being converted. This means that although the conversion could change the reference type, the type or value of the referred to object is never changed.

Boxing and Unboxing Conversion

A boxing conversion allows any value type to be converted to the type object or to any interface type that is implemented by the value type. Boxing a value means allocating an object instance and then copying the value to that instance.

Unboxing is an explicit conversion. It converts from the type object to a value type or from an interface type to a value type which implements the interface. Unboxing involves checking the object instance to insure that it is a boxed value of the given value type. The next step in the unboxing operation is copying the value from the instance into the value type variable.

It is important to remember that you should avoid boxing/unboxing operations in cases where you’re needing to do repetitive assignments. By avoiding this overhead you can improve the performance of your program.


Theme Provided By Free HTML Layouts