30 August 2007

ReSharper vs C# 3.0 - Implicitly Typed Locals

Last month I was on vacation, living in the country, with no access to Internet, doing no programming, reading non-technical books, walking, swimming and otherwise enjoying my life, my family and the nature. It was really-really cool! However, I admit I was thinking a bit about ReSharper features for C# 3.0 and one of the things that puzzled me was

To var or not to var?


Obviously, developer have to use var keyword in case of anonymous types, and can't use var if local variable's type cannot be inferred at the declaration point. But most locals are suitable for both forms - explicit type and var keyword. Context action to switch from explicit type to var and back is okay, but we would like to analyse the code and suggest using var in cases where it will improve the code.

Some cases where it seems just fine to suggest var are:

  1. New object creation expression: var dictionary = new Dictionary<int, string>();

  2. Cast expression: var element = (IElement)obj;

  3. Safe Cast expression: var element = obj as IElement;

  4. Generic method call with explicit type arguments, when return type is generic: var manager = serviceProvider.GetService<IManager>()

  5. Generic static method call or property with explicit type arguments, when return type is generic: var manager = Singleton<Manager>.Instance;



However, various code styles may need to suggest in other cases. For example, programming in functional style with small methods can benefit from suggesting every suitable local variable to be converted to var style. Or may be your project has IElement root interface and you just know that every variable with "element" name is IElement and you don't want explicit types for this case. Probably, any method with the name GetTreeNode() always return ITreeNode and you want vars for all such local variable.

Currently, we have two suggestions: one that suggests every suitable explicitly typed local to be converted to implicityly typed var, and another that suggests according to rules above. They work fine within the team. I hope EAP will give us some feedback about how it works, but Early Access Program for ReSharper 4.0 will be opened later this year.

Meanwhile, do you have any ideas, suggestions or examples where you'd like to see suggestion to convert explicitly typed local variable to the var form?