Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
The var war is brewing

When C# 3.0/.Net 3.5 was released one of the new features that was included was the 'var' keyword.  Now I have to admit that when I first read about this new feature I immediately associated this 'var' with the Variant of VB6 or the var of JScript.  But that could not be future from the truth.

The 'var' keyword was created to allow for anonymous types, these are types that at design time (code time if you will) do not have a concrete type, but at run time they do (compiler creates the concrete type for you).  The var keyword is statically typed, it is not a new version of the Variant.  Take a look at the code below:

// Valid
var someVariableName = "Foo"; // this is typed as a string

// Invalid
var someVariableName = new SomeObject();
someVaraiableName = "Foo"; // this is NOT allowed

Enough of the history lesson, on to the point. 

The use of the var keyword has had some controversy since it was announced, but as of late this 'var' war has heated up with some recent blog posts.  Most notably there have been 2 posts that kinda sum up the general over all feeling on var.  One for the general use and one against the general use of it.

In Jeff Atwood's (aka Coding Horror) post he talks about using var to remove redundancy.  However, in Richard Dingwall's posts he thinks that Jeff has it all wrong.  Well, I am here to tell the world that they are both wrong, yet both right (wow, what a way to pick a side Derik)...

No really, to be honest I was NOT in favor of the var keyword at first, but after giving it some thought and use, I LOVE the var keyword.

In Jeff's post he likes the var because he thinks it removed redundancy from your code (I 100% agree with this). However, Richard counters that saying that the use of var reduces readability. Well, again they are both right, but Jeff is soo much more right than Richard.

So, if I think they are both right, then how do I code an use the var?  here are my rules for when the var should be used versus not used.

  1. Var should be used in all cases where the type can be visually inferred from the right side of the statement:

    // Use var
    var foo = "string";
    var anotherFoo = new Object();

    Both above we know the static type by looking at the code
  2. Var should NOT be used when rule 1 is not true:

    // DO NOT USE var
    var person = someObject.GetPerson();

    Above I can assume that the GetPerson returns me a person object, but I am not 100% sure.  In this case I would rather see something like below.

    Person person = someObject.GetPerson();

Ok, now that I have cleaned up the 'var' war and everyone is happy again, it is time to tackle a larger problem like how to get my wife to allow me to have an iPhone.  Wish me luck.

Till next time,

[----- Remember to check out DimeCasts.Net -----]


Posted 06-25-2008 5:30 AM by Derik Whittaker
Filed under: ,

[Advertisement]

Comments

Andrew Tobin wrote re: The var war is brewing
on 06-25-2008 8:06 AM

The one thing about this "debate" that annoys me is that people keep talking about if var is good based on those simple examples:

var person = new Person();

How about those Anonymous Types where you can create your own classes on the fly?

var person = { Name = "Andrew", Age = 30, Address = new Address { Street....}};

Or when you create them by defining a few columns to select from a LINQ query?

It's frustrating to me that the debate seems to begin and end at whether it's readable given that you're only discussing whether you should use var to shortcut type declarations.

Anyway, that's my 2c.

Thanks

Derik Whittaker wrote re: The var war is brewing
on 06-25-2008 8:14 AM

@Andrew,

I cannot say that I agree 100%.  The reason that most people do not debate the need/likeness for var when talking about anonymous types or linq is because use of a var is the ONLY way this will work.

Were the debate comes in is should they be used to

a) save me a few keystrokes

b) shortcut the need to type in the 'type' multiple time.

Dew Drop - June 25, 2008 | Alvin Ashcraft's Morning Dew wrote Dew Drop - June 25, 2008 | Alvin Ashcraft's Morning Dew
on 06-25-2008 8:29 AM

Pingback from  Dew Drop - June 25, 2008 | Alvin Ashcraft's Morning Dew

Andrew Tobin wrote re: The var war is brewing
on 06-25-2008 8:35 AM

@Derik,

Sure, mate, but the debate makes it seem like the sides are that var is or isn't useful, and should or shouldn't be used based on that alone.

I may be wrong, but most of the time I don't see enough mentioned on anonymous types and the usefulness of var, outside of the shortcut scenario.

I just think the debate undercuts that.

I mean, don't get me wrong - I totally agree with what you've said in your post, it just frustrates me that not enough attention is paid on the other reasons var is there.

As a bit of a n00b, it's frustrating when anonymous types are a fantastic shorthand and utility, that more attention is paid to whether or not you should shorthand a declaration.

You did mention anonymous types and linked it, so maybe I'm just being a bit of a dork by bringing that up - but the debate makes it seem like that's all it's about.

Michael C. Neel wrote re: The var war is brewing
on 06-25-2008 8:58 AM

I'm leaving var to just LINQ results and other anonymous types.  The difference is nil between

var s = "hi"

string s = "hi"

Because of the intellisense and tab I'm only typing "str[tab]" anyway.  And the bigger crime here is the "s" - there is no reason for short variable names, so this should have been "subject" - which also goes against the "less keystrokes" argument.

I've worked a good deal with Python, and if var were truly a dynamically typed variable I would say it had uses out side of LINQ results; just saving keystrokes though isn't enough for me to say it's a good idea elsewhere

Joshua Flanagan wrote re: The var war is brewing
on 06-25-2008 10:13 AM

var is not about saving keystrokes.

I think contributions to the "var war" may provide some insight to non-believers why some of us like it in more scenarios than most:

flimflan.com/.../ToVar.aspx

flimflan.com/.../LosingYourTypeReligion.aspx

Bill Sorensen wrote re: The var war is brewing
on 06-25-2008 1:22 PM

I'm assuming you don't apply the rules to cases where you HAVE to use var, such as certain LINQ statements.

To me the big advantage comes when combining declaration and initialization, especially for generic types:

Dictionary<string, string> input = new Dictionary<string, string>();

Var supports the DRY principle here.

I think I'd also make an exception for local foreach variables. How often have you had to look up the item type of an enumeration just so you could specify it in a foreach statement?

foreach (PropertyInfo property in aType.GetProperties())

Scott Bellware wrote re: The var war is brewing
on 06-25-2008 2:43 PM

> // DO NOT USE var

> var person = someObject.GetPerson();

I have no problem with var here.  I don't particularly write code to express compiler and runtime constraints like data types.

I'd prefer that the var keyword be removed from the language entirely so that I could write:

person = someObject.GetPerson();

It's not the var keyword that is causing the implicit strong typing, it's the result of the call on the right hand side of the line of code - be it a call to the constructor or to a factory method.

I write code to express intent.

Chris Sutton wrote re: The var war is brewing
on 06-25-2008 5:30 PM

Derik,

If .GetPerson() doesn't return a Person or derived type, wouldn't your method naming be misleading?

Supposing your method names were accurate, I think var would be a valid option for the second example.

Chris

Derik Whittaker wrote re: The var war is brewing
on 06-25-2008 5:46 PM

@Chris,

Well yes you are right.  But I could not come up with a quick example.

The point was that i do not like to use var when the method being called does not imply the object type that is being returned.

Mufasa wrote re: The var war is brewing
on 06-25-2008 6:26 PM

Would I read Jeff's post I thought to myself and came up with exactly the same rules you did here in this post. So, thumbs up from me.

Reflective Perspective - Chris Alcock » The Morning Brew #123 wrote Reflective Perspective - Chris Alcock &raquo; The Morning Brew #123
on 06-26-2008 3:12 AM

Pingback from  Reflective Perspective - Chris Alcock  &raquo; The Morning Brew #123

Jay Kimble wrote re: The var war is brewing
on 06-26-2008 9:38 AM

Derek,

I was gonna blog the same thing... thumbs up from me too!

I think you nailed it...

Jay

Christopher Bennage wrote re: The var war is brewing
on 06-26-2008 11:54 PM

I've fallen in love with var recently (R#4 has played Cupid).  

I like how some code becomes so much easier to read, such as:

var example = new ReallyLongClassNameProbablyWithGenericsToo();

I shy away from using var though when it comes to int, string, bool, etc.  I feel that it tends to obscure the intent in those cases.  Though I'm less and less hard about rules, and more inclined to ask "how will the person coming after me read this?".

(But ain't that a question with many answers!)

Kamran Shahid wrote re: The var war is brewing
on 06-28-2008 7:41 AM

Nicely Explained

User links about "var" on iLinkShare wrote User links about "var" on iLinkShare
on 08-26-2008 10:00 AM

Pingback from  User links about "var" on iLinkShare

Derik Whittaker wrote Wow, the hatred for ‘var’ lives on
on 08-14-2009 3:41 PM

Here we are almost 2 full years since the var keyword was released to the wild, and only a few short

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)