C# Casting and Type Conversion

C# is statically-typed at compile time, after a variable is declared, it cannot be declared again or assigned a value of another type unless that type is implicitly convertible to the variable’s type.

For example, the string cannot be implicitly converted to int. Therefore, after you declare i as an int, you cannot assign the string “Hello” to it.

Implicit Conversion

No special syntax is required because the conversion is type safe and no data will be lost.

Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.

Explicit Conversion

Explicit conversions require the cast operator (). Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.

Continue reading

C# Boxing and Unboxing

When the CLR boxes a value type, it wraps the value inside a System.Object instance and stores it on the managed heap.

Boxing is implicit; Unboxing is explicit.

Permormance

Boxing and Unboxing are computationally expensive processes.

When a value type is boxed, a new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally.

Boxing

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type.

Boxing is used to store value types in the garbage-collected heap. Boxing a value type allocates an object instance on the heap and copies the value into the new object.

Unboxing

Unboxing extracts the value type from the object.

Continue reading