Search code examples
c#.netboxing

Is boxing involved when calling ToString for integer types?


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?


Solution

  • 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().