#1,052 – Boxing Is a Kind of Implicit Conversion

Boxing is the process of copying a value-typed object to a new instance of a reference-typed object.  Boxing operations are classified as implicit conversions, in that you are converting between types in a way that is guaranteed to succeed and does not require a cast operator.

Below are some examples of boxing operations.

        public interface IDistance
        {
            double CalcDistance();
        }

        public struct Point3D : IDistance
        {
            public double X, Y, Z;

            public double CalcDistance()
            {
                return Math.Sqrt(X*X + Y*Y + Z*Z);
            }
        }

        public enum Mood { Crabby, NotSoCrabby };

        static void Main(string[] args)
        {
            // Three kinds of value-typed objects
            Point3D pt;
            pt.X = 1.0;
            pt.Y = 2.0;
            pt.Z = 3.0;

            int i1 = 12;
            int? i2 = null;

            // Convert to object
            object o = pt;
            o = i1;
            o = i2;

            // Convert to dynamic
            dynamic dyn1 = pt;
            dyn1 = i1;
            dyn1 = i2;

            // Convert to System.ValueType
            ValueType vty = pt;
            vty = i1;
            vty = i2;

            // Convert to interface implemented
            // by the value type
            IDistance idist = pt;
            double dist = idist.CalcDistance();

            // From enum value to System.Enum
            Mood myMood = Mood.NotSoCrabby;
            Enum genEnum = myMood;
        }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,052 – Boxing Is a Kind of Implicit Conversion

  1. Pingback: Dew Drop – March 13, 2014 (#1742) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: