Why should I use implicitly typed local variables?

Viewed 16429

When I say

public static IMyType GetGateWayManager()
{
    IUnityContainer _container = GetContainer();
    IMyType _gateWayManager = _container.Resolve<IMyType>();
    return _gateWayManager;
}

it comes with a warning saying Use implicitly types local variable.

If I change it to

public static IMyType GetGateWayManager()
{
    IUnityContainer _container = GetContainer();
    var _gateWayManager = _container.Resolve<IMyType>();
    return _gateWayManager;
}

it is fine.

Can anyone can tell me why the VS editor thinks it is best practice to use var here?

6 Answers

The approved answer is certainly correct and answers the question as described.

But - I did want to bring up a case where you have to use implicit typing: when the variable represents an anonymous type.

Consider this code:

var upperLowerWords =
    from w in words
    select new { Upper = w.ToUpper(), Lower = w.ToLower() };

What type is upperLowerWords supposed to be? You can't say, because there is no explicit type that matches what is returned - but it is a type that the compiler can recognize. And, in fact, it does.

For reference: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables (which is where I got that example)

Related