Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ToString() here good, bad, or simply redundant?

Tags:

c#

.net

tostring

Both of these are accepted by the compiler:

ssMinnow = listStrLineElements[VESSEL_TO_AVOID].ToString();
ssMinnow = listStrLineElements[VESSEL_TO_AVOID];

Is one way preferable to the other? ToString() or not ToString(), that is the question.

like image 463
B. Clay Shannon-B. Crow Raven Avatar asked Feb 13 '12 16:02

B. Clay Shannon-B. Crow Raven


4 Answers

It is not only redundant, but also is dangerous: if listStrLineElements[VESSEL_TO_AVOID] happens to be null, your application is going to throw an exception if you use ToString(); without ToString(), it would simply assign null to ssMinnow.

like image 90
Sergey Kalinichenko Avatar answered Sep 27 '22 22:09

Sergey Kalinichenko


If listStrLineElements[VESSEL_TO_AVOID] returns a string, then yes, it is redundant. if it returns some other type, then no, it is not redundant.

like image 31
ColinE Avatar answered Sep 27 '22 23:09

ColinE


in General your don't need to invoke the ToString() method is the object type returned is already a String.

in your example we cannot tell that as ssMinnow does not show the declaration type :I assume you have used var keyword which will work with both of them or listStrLineElements[VESSEL_TO_AVOID] returns already a String

like image 39
Massimiliano Peluso Avatar answered Sep 28 '22 00:09

Massimiliano Peluso


Simply redundant. I prefer to leave off ToString() where its not needed but its a judgement call.

like image 30
heisenberg Avatar answered Sep 27 '22 23:09

heisenberg