Reputation: 11479
I'm trying to explain boxing to a junior colleague.
The canonical example seems to be ArrayList
. For example:
But this has been superseded by List<T>
from C# 2, when generics were introduced (as explained in this answer).
So, in the age of generics, under what circumstances would I find myself boxing values?
Edit: To be clear, I'm not asking whether it is still possible to use boxing. I'm asking why we would use boxing now that generics have made ArrayList
obsolete.
Edit 2: I thought this was already clear, but I'm also not asking about the difference between an ArrayList
and a List<T>
. In fact, this question is entirely premised on the fact that I appreciate that generics mean we don't have to use an ArrayList
, and we therefore don't need to box values in these circumstances.
Upvotes: 3
Views: 184
Reputation: 62015
Boxing and unboxing is not something that you explicitly do; it is something that happens all the time whenever you have a struct
in your hands and you are passing it to some receiver that expects an object
. So, consider this code:
public void SafeToString( Object a )
{
if( a != null )
return a.ToString();
return "null";
}
SafeToString( 42 );
If you had said 42.ToString()
there would be no boxing, because 42 is known by the compiler to have a ToString()
method, and struct
cannot be subclassed, so the ToString()
method that operates on 42 is known at compilation time.
However, when you say SafeToString( 42 );
the 42 gets boxed into an object, which is passed to SafeToString()
, which invokes Object.ToString()
, which resolves to the boxing object's ToString()
, which delegates to int.ToString()
.
Upvotes: 3
Reputation: 21999
Generics is a good thing, but they aren't capable completely remove the necessity of dealing with boxing.
ArrayList
is obsolete, right, but sometimes you still going to use List<object>
when storing different types in one list (when only Object
is something they have in common).
Another example generic methods. Again, they are good if you know type at compile-time, but what if you want something to work with any type? Good old object
parameter and boxing (with casting) to the rescue.
Upvotes: 2