Alex Rivera | Logout

Why should I use implicitly typed local variables?

Asked 2010-08-27T08:34:42.983
21

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?

Edit
Report

2 Answers

22

Who are types for?

The compiler? Yes, absolutely. The compiler uses types to make it more likely that your program will function correctly at runtime by ensuring the types match up, you're calling methods that actually exist, and passing them parameters of the right type. Here, the compiler is checking that you're actually returning something of type IMyType.

The editor? Again, yes. The editor uses background compilation and type information to help you write code. When you hit . after _container it uses type information to tell you that there's a Resolve method and what parameters it takes.

You? Not so much. We've already seen that the compiler will ensure that you return something of type IMyType, so why do you care about declaring it as that type when the compiler can work it out and check it for you? Similarly, the editor will tell you about the methods on the container, so why do you care about declaring whether it's a Unity container or some other type of container, given you already know from the variable name it's a container of some kind and from the editor that it has a Resolve method.

There's no problem with declaring types for locals, but what ReSharper is telling you is that the compiler can work it out, so it's redundant information, and that your code could be clearer with implicit types and good variable names. For example, is the purpose of this code any less clear than the original sample?

public static IMyType GetGateWayManager()
{
    var container = GetContainer();
    var gateWayManager = container.Resolve<IMyType>();
    return gateWayManager;
}
answered 2010-08-27T08:45:15.033
2

It's probably not the VS Editor, but rather ReSharper that is giving you that message. It's more a matter of taste than of best practice. But once you get used to the var keyword, you start to like it more and more. At least I've learned to love it.

answered 2010-08-27T08:37:52.303

Your Answer