Beginning from C# 3.0 version developers can write short keyword var instead of explicitly typed local variable. You can find it’s cozy to write these three letters instead of long explicit type. There is no performance impact when using var because the resulting IL is identical to explicit types.
But there is a big drawback with implicit type var when you stumble upon code you wrote some days, months or years ago. Even worse if you stumble upon code from another developer. It can take more time to understand code where var placed instead of explicitly typed local variables.
For myself I formed the next main rule when to use explicit and when anonymous types for local variables: “Think about those who will read your code and don’t forget you are a reader too”.
1 2 3 4 5 6 7 8 9 10 |
// Use 'var' when it's obvious what type is constructed var myVar = new SomeType(); // It's better to write explicit type for method result SomeType someObject = SomeMethod(); // But instead of unreadable ISomeComplexGeneric<IList<TEntity>, IDictionary<TEntity, IList<int>> someComplexGeneric = SomeMethodThatReturnsComplexGeneric(); // it's better to write 'var' var someComplexGeneric = SomeMethodThatReturnsComplexGeneric(); |
For ReSharper users there is a handy trick for quick writing explicit type you are not remember of. Just write
1 |
var someObject = SomeMethod(); |
then set cursor to ‘var’, press Alt + Enter(or what hotkey you set for R# quickfix operation) and choose ‘Specify type explicitly’. Anonymous ‘var’ will turn into non-anonymous type.