Question about Boxing

  • Thread starter Thread starter Sam Kong
  • Start date Start date
S

Sam Kong

Hello!

I am trying to understand Boxing and Unboxing.
I think I understand most of them except the following.
From Mr. Eric Gunnerson's article
(http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp03152001.asp)

One of the points of being able to box is so that virtual functions can
be called on value types, and ToString() is a virtual function on
object, so it would appear that d would be boxed when ToString() is
called. However, we haven't used d in a situation where it would get
converted to an object, so a box isn't required. The compiler knows
that a variable of type DateTime can only be that type (it can't be a
derived type, since there are no derived value types), so it can call
DateTime.ToString() directly and set the "this" reference to point to
the d instance on the stack.

Does that mean that calling a virtual method have nothing to do with
boxing?


TIA.
Sam
 
I don't know about "nothing to do with boxing"... the example that Mr.
Gunnerson gave was of a value type that explicitly implements
ToString(). Since value types don't participate in the inheritance
hierarchy (except to inherit from Object), the compiler can call
ToString() directly: it doesn't have to worry about polymorphism.

However, what about a value type myStruct that doesn't implement
ToString()? If you call ToString() on it then the compiler must insert
a call to the default (Object) implementation of ToString(). What
happens then? Does myStruct have to be boxed so that there is an object
instance on which to run the generic ToString() method? Or are there
other tricks going on under the covers? I must admit that I don't know.

The example explains that if your value type explitly implements a
virtual method (of which there are only three: Equals(object),
GetHashCode(), and ToString()) does not need to be boxed in order to
call the method.
 
Back
Top