Tuesday, 16 March 2010

C# var recommendations

With a recent move to .NET 3.5 we’re beginning to review our coding standard and consider some of the things C# 3.0 makes available to new and experienced developers alike. One of these things is the contentious var keyword.

‘var’ seems to instil fear into some developers with others viewing it as total awesomeness. Like all things, var has its place for storing anonymously typed objects returned from the likes of a LINQ query but can it really be misused?

While var does at first glance appear to be a merger of JavaScript and VB with C#, it’s important to note the use of the var keyword must comply with the following:

  • A variable declared using the var keyword must be initialised within the same statement
  • An object with a different type cannot be assigned in a subsequent statement
  • Variables declared with a type of ‘var’ are strongly-typed and compile-time checked; instead of having to determine the type yourself, the compiler does it for you
  • Intellisense will continue to work wherever the variable is used
  • The var keyword can only be used for local variables within a method

Commenters responding to a blog post by Steven Wellens on the use of the var keyword also cited an improved refactoring experience; I partially agree with this point however Visual Studio’s refactoring tools largely take care of those problems.

The main reasoning by commenters was for (and against) readability and I agree strongly that using var reduces “noise” words in the code. In my view, this improves the ability to easily scan the code.

The example statement Steven supplied was claimed to be unreadable—but primarily for the poor name chosen for the GetData method:

var data = GetData();

If the method is renamed, this does remain a gray area unless it also includes type information in the name, which is yucky. Removing type information does allow intent to shine through of course—not a bad thing.

With this preface, here are the draft recommendations for use of the var keyword in our shop:

  • Do declare the type if it's useful otherwise use 'var' to avoid "noise" where type information is unimportant or can be read in the object's initialisation. Eg: var cat = new Cat ();
  • Do use 'var' to highlight intent over implementation detail
  • Do use 'var' as required for anonymous types
  • Consider readability; avoid examples like var data = GetData(); where the type returned by GetData() is not obvious

References

No comments:

Post a Comment

Spam comments will be deleted

Note: only a member of this blog may post a comment.