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?
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_containerit uses type information to tell you that there’s aResolvemethod 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 aResolvemethod.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?