ToString() considered Harmful

When I was studying, Dijkstra had this famous anecdote that "Goto" statements are considered harmful and hence should be conisdered illegal! (http://www.cs.utexas.edu/users/EWD/transcriptions/EWD02xx/EWD215.html)

I put forwrard a similar case for ToString(). Generations of programmers have been brought up to do ToString() without checking null and causes all kinds of harmful side effects long after the program is written.

C# has given us a wonderful keyword called "as" which essentially encapsulates the following

if(null != <your variable>
{
   <another variable> = <your variable>.ToString()
}

So next time you are writing ToString() or toString() or another variant ... consider it carefully and use the above construct instead.
It is also a good practice as part of Defensive Programming.

 del.icio.us  Stumbleupon  Technorati  Digg 

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this entry.
Comments

  • 3/9/2010 12:23 PM Rahul Gautam wrote:
    I think the best option is, to not use the ToString() all together. Instead the Convert.ToString(); serves our purpose very well and it also handles the null values, which is not done by the .ToString() construct.

    = Convert.ToString();
    Reply to this
  • 3/9/2010 12:30 PM Rahul Gautam wrote:
    Of Course this is just for C# .net codes!!
    Reply to this
Leave a comment

Submitted comments will be subject to moderation before being displayed.

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.