Implicitly typed variables in C# using var

I’m finally going to jump into the var keyword debate.  This has been nagging me for a long time and now I’m going to say it.  I hate ‘var’ for the simple reason that it makes code significantly less readable.  I understand it’s strongly typed and I’m not against it’s functionality.  The problem is I like to instantly know what the type of a variable is, I don’t like having to analyze the code to figure it out.  Hovering the mouse over the keyword to get the type is an extra step that takes additional time and hassle when reading through code.

I’m a firm believer in writing descriptive methods and variable names.  It can be difficult to take an extra moment to come up with a good name but in the long run the code is much easier to follow.  So part of me thinks that descriptive names should be more than enough to offset the context provided by the explicit type but even a descriptive name takes an extra moment of mental processing to comprehend.

A valid argument can be made that object creation without var is a bit redundant.  SomeType s = new SomeType();  Do we really need both SomeTypes in there?  Probably not but what happens when an object is returned by a method?  SomeType s = foo.GetAnObject();  Now SomeType is only in there once and if var is used instead, we’ve lost all context for the type of the object.

The real problem here is that this debate is a personal preference.  There will be people who prefer the concise and non redundant format provided by the use of var and there will be people who want to know the type without thinking twice.  I guess you now know which side of the fence I fall on.

My inspiration to chime in on this topic came from this blog post.  Richard’s argument is similar to mine but I found the comments from his readers interesting.  It simply comes down to preference.


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