My Software Notes

Useful things I discover

“var” is a pronoun

with one comment

One of the great features of C# 3.0 is the new “var” keyword.  It allows the type of your local variables to be inferred and thus saves you from too much typing (no pun intended).

For example, instead of having to type:

MyClassWithAnIncredblyLongName foo = new MyClassWithAnIncredblyLongName();

You can type:

var foo = new MyClassWithAnIncredblyLongName();

However, this convenience can be taken too far.  When I first started using C# 3.0 I got all enthusiastic about using var, but it didn’t take me long to recognize the pitfalls.  It’s fine to use “var” as in the example above, but what about this:

var guyToHandle = GetTheGuy(someVariable);

So what type is guyToHandle? Sure you can move the mouse over “var” in Visual Studio and the tool tip will tell you, but wouldn’t it be easier to read and therefore maintain if it said:

Employee guyToHandle = GetTheGuy(someVariable);

Now with just a quick look you can see what the type is. No mouse required.

The equivalent in the English language to “var”is a pronoun and similar problems can occur when a pronoun is misused:

Joe and Bill were talking and he said “blah, blah, blah”.  Which “he” is it?  Hence the title of this post.

As with any language feature, “var” is a tool to use for the appropriate job.  So use it wisely.


Written by gsdwriter

March 4, 2009 at 11:57 am

Posted in Languages

Tagged with ,

One Response

Subscribe to comments with RSS.

  1. […] on this blog I posted about using “var” in C# (“var” is a pronoun).  In it I said you should only use it when it was obvious what the data type is.  Well, […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: