Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of "Boxing" in C# (as opposed to Java)?

Tags:

java

c#

I'm learning C# from a Java background and had some confusion about ValueTypes. My understanding from reading MSDN's C# vs Java overview was that primitives are objects instead of having wrappers. If that's the case, why do they need to be boxed to call methods? It looks like they mean something different than Java's autoboxing, but I'm not sure what. It looks more like casting.

like image 949
user2899059 Avatar asked Nov 17 '14 13:11

user2899059


1 Answers

Boxing is very similar concept in Java and C#. The difference is when it happens:

Character ch = 'a';

this will cause boxing in Java because 'a' is primitive and Character is class (wrapper). In C# this:

Char ch = 'a';

will not cause boxing because Char is not a primitive type but is value-type class. To cause boxing in C# you need to cast object of value type to object reference.

object o = 'a';

Edit: As mentioned by HighCore in comment, there is important implication of the boxing mechanism in C#. Putting stuff into List<int> doesn't cause boxing and taking stuff out doesn't cause unboxing because List of ints is real list of unboxed ints.

like image 193
Andrey Avatar answered Oct 08 '22 03:10

Andrey