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:
- New object creation expression: var dictionary = new Dictionary<int, string>();
- Cast expression: var element = (IElement)obj;
- Safe Cast expression: var element = obj as IElement;
- Generic method call with explicit type arguments, when return type is generic: var manager = serviceProvider.GetService<IManager>()
- 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?