Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant ToString code?

Tags:

c#

.net

resharper

I was wondering :

writing this code :

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

Resharper shows it like : ( notice the gray )

enter image description here

enter image description here

3 questions please

1) removing ToString() , how will the object will output its display string without calling the removed ToString() ?

2) does it suggest to remove it because he already calls it internally ? or because of another reason ?

3) not removing ToString() , will it call it twice ?

like image 655
Royi Namir Avatar asked Dec 15 '22 17:12

Royi Namir


1 Answers

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

Actually it uses the ICustomFormatter.Format method on every provided parameter.

It's also redundant in terms of useless. So even if no work needs to be done multiple times(AppendFormat will not try to convert a string to a string), it is pointless since AppendFormat would do it anyway. Hence resharper tries to simplify your code here.

like image 198
Tim Schmelter Avatar answered Dec 18 '22 06:12

Tim Schmelter