#1,062 – Unboxing Conversions
March 27, 2014 1 Comment
If you’ve converted a value-typed object to a reference-typed object by boxing it, you can later unbox the object, converting it back to a value type. Unboxing is an explicit conversion and requires a cast operator.
Below are some examples of unboxing conversions.
public interface IArea { double CalcArea(); } public struct MyPoint : IArea { public double X; public double Y; public MyPoint(double x, double y) { X = x; Y = y; } public double CalcArea() { return X * Y; } } static void Main(string[] args) { int i1 = 12; object o = i1; // Boxing - implicit // Unbox from object to value type int i2 = (int)o; // Boxing - explicit conversion // Unbox from dynamic dynamic d = i1; int i3 = (int)d; // Boxing, implicit, creates new copy MyPoint pt = new MyPoint(2.0, 3.0); IArea area = pt; // Unboxing, explicit, // from interface to value type, // creates new copy again MyPoint pt2 = (MyPoint)area; // Unbox to nullable type int? i4 = (int?)o; o = null; int? i5 = (int?)o; // also works // Boxing, implicit, to ValueType // (creates copy) ValueType vty = pt; // Unboxing, creates copy MyPoint pt3 = (MyPoint)vty; }