Question about Boxing

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
 
B

Bruce Wood

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Why boxing? 1
Boxing m.m 2
Boxing and UnBoxing 5
boxing when calling ToString on a struct object 4
Question on boxing 5
Dictionary of classes 3
about performance 2
Question on boxing 2

Top