C# Boxing and Unboxing

Boxing: Act of converting a value type instance to a reference type instance. Example: int x = 9; object obj = x; Unboxing: Reverses the operation by casting the object…

Boxing: Act of converting a value type instance to a reference type instance.

Example:

int x = 9;

object obj = x;

Unboxing: Reverses the operation by casting the object back to the original value type:

Example:

int y = (int)obj;

Unboxing requires an explicit cast. The runtime checks that the stated value type matches the actual object type, and throws an InvalidCastException if the check fails.

Boxing copies the value type instance into the new object, and unboxing copies the contents of the object back into a value type instance.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *