Is boxing involved when calling ToString for integ

2019-04-05 04:58发布

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?

标签: c# .net boxing
6条回答
劫难
2楼-- · 2019-04-05 05:21

Since ToString is overriden in Int32 class - no, there will no boxing in this case as no instance on object will be created.

Simply appropriate method of Int32 is called because of dynamic dispatch.

查看更多
虎瘦雄心在
3楼-- · 2019-04-05 05:35

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.

查看更多
萌系小妹纸
4楼-- · 2019-04-05 05:35

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/

查看更多
放我归山
5楼-- · 2019-04-05 05:35

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.

查看更多
Melony?
6楼-- · 2019-04-05 05:42

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 overridden ToString() method. It does not have (and cannot have) an overridden GetType() method.

int? i = null;
var s = i.ToString(); // okay: initialises s to ""
var t = i.GetType(); // not okay: throws NullReferenceException

This shows that there is no boxing in the call i.ToString(), but there is boxing in the call i.GetType().

查看更多
不美不萌又怎样
7楼-- · 2019-04-05 05:46

The other answers mention that the ToString call will not result in boxing. It's worth nothing 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)

查看更多
登录 后发表回答