I\'ve often wondered if the following scenario actually happens in c#
If I have a struct but I don\'t explicitly override any of the methods that derived from objec
No it's not boxed when you call ToString
or GetHashCode
if it's implemented by your struct (why should it? constrained IL instruction takes care of it.) It's boxed when you call a non-virtual method (or a virtual method not overriden in the struct) on System.Object
(its base class), i.e. GetType
/MemberwiseClone
.
UPDATE: Sorry for the misunderstanding it may have caused. I wrote the answer with overriding the methods in the struct in mind (that's why I mentioned non-virtual methods need boxing, I should have been more explicit not to confuse readers, especially since I missed your statement regarding not overriding the method) as if you don't override it, the Object.ToString
method expects it's first argument (reference to this
) to be a reference type (an Object
instance). Obviously, the value has to be boxed in that call (as it's a call in the base class.)
However, the point is, the nature of calling a virtual method on a value type does not result in emitting the box
instruction (unlike non-virtual methods on Object
that always result in emitting an explicit box
instruction.) It's the callvirt
instruction that will do the boxing if it has to resort to the Object.ToString
implementation (as you mentioned in the updated question) just like when you are passing a struct to a method that expects an object
parameter.