all groups > dotnet academic > march 2007 >
You're in the

dotnet academic

group:

c# structs and boxing



c# structs and boxing Filip De Backer
3/16/2007 1:42:05 AM
dotnet academic: Hi everybody,

I've read in the MCTS examn 70-368 book (page 58) that you must implement an
override for the ToString() method for each struct you create. If you do
that, there won't be any boxing. Boxing occurs when you call virtual method
that a structure inhirits from system.object (for exemple toString is such a
method)

But when you create a struct with an int as member (int var;)
and in this struct you have a ToString override method which "return
this.var.toString();" in it, than this is also boxing or am I wrong?

thanks for the answers

RE: c# structs and boxing Manoj Kumar
3/27/2007 4:12:53 PM
In this particular, boxing will not take place. If you will make a short
program for this and check the IL emitted from it then you will notice a
'constrained' opcode on your structure and a 'callvirt' opcode for calling
your overriden ToString() method.

In this case MSDN states that
If the Type[structure here] is a value type and Type does not implement
method then ptr[a pointer on the stack] is dereferenced, boxed, and passed as
the 'this' pointer to the callvirt method instruction, and this only happens
when method was defined on Object, ValueType, or Enum and not overridden by
your Type.

for more information check out MSDN callvirt and constrained opcoodes.
--
Manoj Kumar

[quoted text, click to view]
AddThis Social Bookmark Button