Pet Peeve 318: (string) vs ToString()

I’m trying to make it a point to blog entries on a regular basis. I’ve been told its a good idea, and I like good ideas, but at this time of the day, I don’t have much to talk about.

So, I’m going to fall back to Jay Pet Peeve #318 (I just made that up, but I’ll start keeping track.)

Let me be upfront about Pet Peeve #318: It is superceded by Pet Peeve #277. If you have to do a lookup by string, then its covered by #277. However, I feel you should do the lookups by ordinal, which is covered by the next post.

ToString()

select FirstName, ShoeSize from SomeStupidTableThatDoesntActuallyExist

The name is a varchar, and the shoesize is an integer.

You write some code to execute the query, and you end up with a data reader. Then you start looping through the reader.

while (reader.Read()) {
Console.WriteLine(“First Name: ” + reader[“firstname”].ToString());
Console.WriteLine(“Shoe Size: ” + reader[“shoesize”].ToString());
}

An alternative for first name is:
Console.WriteLine(“First Name: ” + (string)reader[“firstname”]);

The first approach is technically sound, though I prefer the second simply for semantics. ToString() is used to provide the string representation of an object. When your object is already a string, you’re essentially saying “convert my string to a string”. Whereas, the 2nd approach says “here’s my string”. You wouldn’t do “hello”.ToString(), would you?

Does it matter? No. Its a pet peeve. I tried to be upfront about that. Pardon me if I wasn’t clear.

As for the “shoesize”, that’s a different story. That’s an integer, but you want to display it as a string, so ToString() doesn’t offend my delicate sensibilities in that case.

NOTE: I don’t like “firstname” and “lastname” in the reader calls either… that’s covered in the next post.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: