Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion regarding boxing of value types

Tags:

c#

In the following code...

 int i=5;  
 object o = 5;
 Console.WriteLine(o); //prints 5

I have three questions:

1) What additional/useful functionality is acquired by the 5 residing in the variable o that the 5 represented by the variable i does not have ?

2) If some code is expecting a value type then we can just pass it the int i , but if its expecting a reference type , its probably not interested in the 5 boxed in o anyway . So when are boxing conversions explicitly used in code ?

3) How come the Console.WriteLine(o) print out a 5 instead of System.Object ??

like image 359
explorer Avatar asked Aug 31 '25 17:08

explorer


1 Answers

What additional/useful functionality is acquired by the 5 residing in the variable o that the 5 represented by the variable i does not have ?

It's rare that you want to box something, but occasionally it is necessary to do so. In older versions of .NET boxing was often necessary because some methods only worked with object (e.g. ArrayList's methods). This is much less of a problem now that there is generics, so boxing occurs less frequently in newer code.

If some code is expecting a value type then we can just pass it the int i, but if its expecting a reference type, its probably not interested in the 5 boxed in o anyway . So when are boxing conversions explicitly used in code ?

In practice boxing usually happens automatically for you. You could explicitly box a variable if you want to make it more clear to the reader of your code that boxing is happening. This might be relevant if performance could be an issue.

How come the Console.WriteLine(o) print out a 5 instead of System.Object ??

Because ToString is a virtual method on object which means that the implementation that is called depends on the runtime type, not the static type. Since int overrides ToString with its own implementation, it is int.ToString that is called, not the default implementation provided by object.

object o = 5;
Console.WriteLine(o.GetType());  // outputs System.Int32, not System.Object
like image 82
Mark Byers Avatar answered Sep 13 '25 04:09

Mark Byers



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!