boxing on structs when calling ToString()

前端 未结 3 1184
轮回少年
轮回少年 2020-12-28 10:31

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

3条回答
  •  [愿得一人]
    2020-12-28 11:02

    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.

提交回复
热议问题