Excess ToString Code?

It was interesting to me:

writing this code:

DataRow[] g = new DataRow[1] ; var t=new StringBuilder().AppendFormat("{0}", g[0]["aaa"].ToString()); 

Resharper shows this as: (pay attention to gray)

enter image description here

enter image description here

3 questions please

1) removing ToString (), how does the object display its display string without calling the remote ToString ()?

2) Does he suggest deleting him because he already calls it internally? or for another reason?

3) without removing ToString (), is it called twice?

+4
source share
2 answers

Yes, it is redundant because an AppendFormat (like String.Format ) internally converts it to a string, and String.ToString always redundant.

In fact, it uses the ICustomFormatter.Format method for each parameter provided.

It is also redundant in terms of worthlessness. Therefore, even if no work should be performed several times ( AppendFormat will not try to convert a string to a string), this is pointless, as AppendFormat will do this anyway. Therefore resharper is trying to simplify your code here.

+8
source

You can see: Composite formatting

Processing order

Each value in the parameter list corresponding to a format element is converted to a string, following the steps in the following list. If any condition in the first three steps is true, the string representation of this value is returned at this stage, and the subsequent steps are not performed.

  • If the value for formatting is null, an empty string ("") is returned.
  • If the parameter of the IFormatProvider type, which also implements the ICustomFormatter interface, is included in the composite formatting method, the value is passed to the ICustomFormatterFormat method.
  • If the value implements the IFormattable interface, its IFormattableToString method is called.
  • The ToString type is called, which is either overridden or inherited from the Object class.

While the DataRow seems to inherit from System.Object and not an implmenet IFormatProvider or IFormattableToString , so I believe its ToString method is called to get the view of the string inside, and having an explicit .ToString is considered redundant.

+4
source

Source: https://habr.com/ru/post/1443210/


All Articles