Under what circumstances will boxing happen in modern C #?

I'm trying to explain boxing to a junior colleague.

The canonical example seems to be ArrayList

. For example:

But that was replaced with List<T>

from C # 2 when generics were introduced (as explained in this answer ).

So, in the era of generics, under what circumstances can I find myself boxing values?


Edit: To be clear, I'm not asking if boxing can be used. I ask why are we going to use boxing now that generics have been ArrayList

deprecated.


Edit 2: I thought this was clear already, but I am also not asking about the difference between ArrayList

and List<T>

. In fact, this question is entirely based on the fact that I appreciate that generics mean we don't need to use ArrayList

, so we don't need to enter values ​​under these circumstances.

+3


source to share


2 answers


Boxing and unboxing is not something you explicitly do; this is what happens all the time that you have it struct

in your hands and you pass it on to some receiver waiting object

. So, consider this code:

public void SafeToString( Object a )
{
    if( a != null )
        return a.ToString();
    return "null";
}

SafeToString( 42 );

      



If you said 42.ToString()

there would be no boxing because 42 is known to the compiler to have a method ToString()

and struct

cannot be subclassed, so a method ToString()

that works for 42 is known at compile time.

However, when you say SafeToString( 42 );

42 gets into an object that is passed to SafeToString()

that calls Object.ToString()

, which resolves the boxing object ToString()

that delegates int.ToString()

.

+3


source


Generics are good, but they cannot completely eliminate the need to deal with boxing.

ArrayList

deprecated, right, but sometimes you're still going to use it List<object>

when storing different types in the same list (when only Object

it's something in common).



Another example of common methods. Again, they're fine if you know the type at compile time, but what if you want something to work with any type? Nice old setting Object

and boxing (with casting) for the rescue.

+2


source







All Articles