Search code examples
c#objectresharpervirtualtostring

Unnecessary casting to object used for calling ToString() in mscorlib


In StringWriter (mscorlib.dll) I found a code:

private StringBuilder _sb;
// (...)
public override string ToString()
{
  return ((object) this._sb).ToString();
} 

I don't see reason for that (so is my R#, but it is sometimes wrong). ToString() is virtual so the casting does not change behaviour.

What kind of optimization is being done here?


Solution

  • It doesn't make any difference and there is no optimization. The generated IL with and without cast is exactly the same. In fact when opening mscorlib with Reflector, it only says return this._sb.ToString();.

    As you said, ToString() is virtual, and it is not marked new in StringWriter, so the generated IL refers to Object.ToString() (the initially declared method) in any case (except for some basic value types):

    ldfld class System.Text.StringBuilder System.IO.StringWriter::_sb
    callvirt instance string System.Object::ToString()
    

    Even looking at the CLI 2.0 Source Code, the code is the following:

    public override String ToString() {
        return _sb.ToString();
    }
    

    The only difference according to Reflector is that StringBuilder.ToString() is unsafe. There is no keyword for this in IL, but it can be found out by checking for unsafe instructions. R# might consider this a difference (although it's not) and prefer to go explicit.