Purpose of boxing and unboxing?
-
Okay, so I'm very new to C# (and to programming in general for that matter), but I've come across this idea of boxing and unboxing that seems completely odd. In my understanding, it is a shell game of sorts between a referenced type and a value type. It seems to me that this might save in resources, and that it is similar to casting in C, but it is unclear to me. If anyone could give a reason as to why someone would want to use this technique, I would be very grateful. "If you really want something in this life, you have to work for it. Now, quiet! They're about to announce the lottery numbers..." - Homer Simpson
-
Okay, so I'm very new to C# (and to programming in general for that matter), but I've come across this idea of boxing and unboxing that seems completely odd. In my understanding, it is a shell game of sorts between a referenced type and a value type. It seems to me that this might save in resources, and that it is similar to casting in C, but it is unclear to me. If anyone could give a reason as to why someone would want to use this technique, I would be very grateful. "If you really want something in this life, you have to work for it. Now, quiet! They're about to announce the lottery numbers..." - Homer Simpson
You can cast anything to the type Object, and back again. This is frequently used when a method takes parameters that can be any data type. For instance the String.Format method:
string s = string.Format("{0}{1}{2}", "The answer is ", 42, ".");
What really happens here is that the method takes an array of objects:object[] temp = new object[] {(object)"The answer is ", (object)42, (object)"."}; string s = string.Format("{0}{1}{2}", temp);
The strings already are objects, so they can be casted without boxing. For the integer value, though, a new object is created on the heap and the value is copied into the object. --- b { font-weight: normal; }