Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what circumstances would boxing occur in modern C#?

Tags:

c#

boxing

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

The canonical example seems to be ArrayList. For example:

  • Understanding Boxing and Unboxing in C#
  • Why do we need boxing and unboxing in C#?

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.

like image 309
Tom Wright Avatar asked Jun 24 '26 15:06

Tom Wright


2 Answers

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().

like image 148
Mike Nakis Avatar answered Jun 26 '26 18:06

Mike Nakis


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.

like image 20
Sinatr Avatar answered Jun 26 '26 17:06

Sinatr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!