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?
The toString() method returns a string representing the specified string value.
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.
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.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With