So I understand what boxing and unboxing is. When's it come up in real-world code, or in what examples is it an issue? I can't imagine doing something like this example:
int i = 123;
object o = i; // Boxing
int j = (int)o; // Unboxing
...but that's almost certainly extremely oversimplified and I might have even done boxing/unboxing without knowing it before.
Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the common language runtime (CLR) boxes a value type, it wraps the value inside a System. Object instance and stores it on the managed heap. Unboxing extracts the value type from the object.
If I look up what unboxing and boxing does you see that the difference is that boxing allocates memory on the heap and unboxing moves a value-type variable to the stack. Accesing the stack is faster than the heap and therefore unboxing is in your case faster.
Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object.
Boxing is an expensive process, since it copies an object from a stack to a heap which requires a number of processor as well as space on the heap. Another disadvantage of using boxing is that the same object appears at two different places in memory which can have contradictory state.
It's much less of an issue now than it was prior to generics. Now, for example, we can use:
List<int> x = new List<int>();
x.Add(10);
int y = x[0];
No boxing or unboxing required at all.
Previously, we'd have had:
ArrayList x = new ArrayList();
x.Add(10); // Boxing
int y = (int) x[0]; // Unboxing
That was my most common experience of boxing and unboxing, at least.
Without generics getting involved, I think I'd probably say that reflection is the most common cause of boxing in the projects I've worked on. The reflection APIs always use "object" for things like the return value for a method - because they have no other way of knowing what to use.
Another cause which could catch you out if you're not aware of it is if you use a value type which implements an interface, and pass that value to another method which has the interface type as its parameter. Again, generics make this less of a problem, but it can be a nasty surprise if you're not aware of it.
Boxing (in my experience) usually occurs in these cases:
Object
.ArrayList
).Other times you can see boxing and unboxing is when you use reflection as the .NET framework's reflection API makes heavy use of Object
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With