c# - does valueType.ToString() does a cast on the valueType? -
lets say, have following code in c#
int x = 0; x.tostring(); does internally boxing of x? there way see happening visual studio?
in specific case, using system.int32 (an int). type redefines tostring, equals , gethashcode, no boxing.
if use struct doesn't redefine tostring you'll have constrained callvirt system.object.tostring(). definition of constrained:
when callvirt method instruction has been prefixed constrained thistype, instruction executed follows:
- if thistype value type , thistype implements method ptr passed unmodified 'this' pointer call method instruction, implementation of method thistype.
- if thistype value type , thistype not implement method ptr dereferenced, boxed, , passed 'this' pointer callvirt method instruction.
so there isn't boxing if value type implements tostring , there boxing if doesn't implement it... interesting. didn't know.
for non-virtual methods gettype() defined in system.object value type boxed. tested a:
5.gettype(); resulting il code:
il_0001: ldc.i4.5 il_0002: box [mscorlib]system.int32 il_0007: call instance class [mscorlib]system.type [mscorlib]system.object::gettype()
Comments
Post a Comment