Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 610
Krzysztof Morcinek Avatar asked Apr 04 '13 07:04

Krzysztof Morcinek


People also ask

What happens if you call toString on a string?

The toString() method returns a string representing the specified string value.

Is toString method automatically called?

toString() gets invoked automatically. Object. toString() 's default implementation simply prints the object's class name followed by the object's hash code which isn't very helpful. So, one should usually override toString() to provide a more meaningful String representation of an object's runtime state.

Is already a string There's no need to call toString () on it?

Since toString() method simply returns the current string without any changes, there is no need to call the string explicitly, it is usually called implicitly.

What does toString () do in C#?

ToString is the major formatting method in the . NET Framework. It converts an object to its string representation so that it is suitable for display.


2 Answers

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.

like image 60
Botz3000 Avatar answered Oct 10 '22 20:10

Botz3000


What kind of optimization is being done here?

None. R# is just wrong here.

Neither ILSpy nor JustDecompile show this strange cast, and I also don't find it in the reference source code.

So the code is just

public override string ToString()
{
    return this._sb.ToString();
}
like image 32
sloth Avatar answered Oct 10 '22 21:10

sloth