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?
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?
Since
ToString
is overriden inInt32
class - no, there will no boxing in this case as no instance onobject
will be created.Simply appropriate method of Int32 is called because of dynamic dispatch.
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 callsbase.ToString()
: then actual instance is boxed and passed toSystem.ValueType.ToString()
Int32.ToString()
does not callbase.ToString()
and use native implemenation, hence no boxing occur.When you decompile the
Int32.ToString()
call you can see it implementsFormatInt32
which is native C++ methods. The method is implemented as follows:Which calls
Int32ToDecChars
:It takes each digit, converts to a separate
char
and stores in a string. The string is then returned. So there is no boxing ofint
involved.Under this link you can find fairly thorough explanation of what actually happens when invoking
ToString()
on anint
. As a bonus the article also explains all the mechanisms behindInt32.Parse()
:https://selvasamuel.wordpress.com/2008/03/14/boxingunboxing-in-net/
It depends on how the ToString() function implemented in Int32 class. Since the implementation done by .net framework, we can't confirm whether boxing happens or not.
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()
.The other answers mention that the
ToString
call will not result in boxing. It's worth nothing a corollary:will not result in boxing, whereas:
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)