Very simple question:
int a = 5;
string str = a.ToString();
Since ToString
is a virtual method of System.Object, does it mean that everytime I call this method for integer types, a boxing occurs?
When you decompile the Int32.ToString()
call you can see it implements FormatInt32
which is native C++ methods. The method is implemented as follows:
public override string ToString()
{
return Number.FormatInt32(
this,
null,
NumberFormatInfo.CurrentInfo);
}
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern string FormatInt32(
int value,
string format,
NumberFormatInfo info);
Which calls Int32ToDecChars
:
wchar_t* COMNumber::Int32ToDecChars(
wchar_t* p,
unsigned int value,
int digits)
{
LEAF_CONTRACT
_ASSERTE(p != NULL);
while (--digits >= 0 || value != 0) {
*--p = value % 10 + '0';
value /= 10;
}
return p;
}
It takes each digit, converts to a separate char
and stores in a string. The string is then returned. So there is no boxing of int
involved.
Under this link you can find fairly thorough explanation of what actually happens when invoking ToString()
on an int
. As a bonus the article also explains all the mechanisms behind Int32.Parse()
:
https://selvasamuel.wordpress.com/2008/03/14/boxingunboxing-in-net/
No, boxing does not occur. When virtual method is called, CLR looks for type object pointer to get actual overrriden method from method table. For value types there is no object pointer, so direct non-virtual call is made instead, JIT knows that there are no polimorphic side-effects because value types are sealed. However, boxing might occur if ToString()
of value type calls base.ToString()
: then actual instance is boxed and passed to System.ValueType.ToString()
Int32.ToString()
does not call base.ToString()
and use native implemenation, hence no boxing occur.
The other answers mention that the ToString
call will not result in boxing. It's worth noting a corollary:
int i = 42;
String.Format("number: {0}", i.ToString());
will not result in boxing, whereas:
int i = 42;
String.Format("number: {0}", i);
will.
(You hear that, Resharper?)
(However, bear in mind that if you're applying a formatter to String.Format
(e.g. CultureInfo
, you need to use the second version)
You've already got answers telling you that when
ToString()
is overridden for a value type, there will be no boxing when you call it, but it's nice to have some way of actually seeing that.Take the type
int?
(Nullable<int>
). This is a useful type because it is a value type, yet boxing may produce a null reference, and instance methods cannot be called through a null reference. It does have an overriddenToString()
method. It does not have (and cannot have) an overriddenGetType()
method.This shows that there is no boxing in the call
i.ToString()
, but there is boxing in the calli.GetType()
.