I'm learning C# from a Java background and had some confusion about ValueType
s. 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With