lets say, i have the following code in c#
int x = 0;
x.ToString();
does this internally does a boxing of x? Is there a way to see this happening from visual studio?
lets say, i have the following code in c#
int x = 0;
x.ToString();
does this internally does a boxing of x? Is there a way to see this happening from visual studio?
In this specific case, you are using a
System.Int32
(anint
). That type redefinesToString
,Equals
andGetHashCode
, so no boxing.If you use a
struct
that doesn't redefineToString
what you'll have is aconstrained callvirt
toSystem.Object.ToString()
. The definition of constrained:So there isn't boxing if the value type implements
ToString
and there is boxing if it doesn't implement it... Interesting. I didn't know.For non-virtual methods like
GetType()
that are defined inSystem.Object
the value type is always boxed. Just tested with a:resulting IL code:
Here is the IL generated by your code:
As you can see no boxing is taking place.
On the other hand, this code
will not surprisingly cause boxing:
Generally, if if the type of
x
is notint
but any value type (struct
) then you have to overrideToString
to avoid boxing. Specifically, a constrainedcallvirt
is emited:If you want to avoid boxing when calling
Equals
,GetHashCode
andToString
on a value type you need to override these methods.