Implicit typing; why just local variables?
Eric Lippert did an entire blog post on the subject.
- https://learn.microsoft.com/en-us/archive/blogs/ericlippert/why-no-var-on-fields
In summary, the main problem is that it would have required a major re-architecture of the C# compiler to do so. Declarations are currently processed in a single pass manner. This would require multiple passes because of the ability to form cycles between inferred variables. VB.NET has roughly the same problem.
Why should I use implicitly typed local variables?
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;
}
Using implicitly typed local variables
I personally only use “var” when I can clearly distinguish the variable Type by just reading the declaration, for example:
var someVariable = new List<int>();
In the example above, its evident that “var” refers to “List<int>”.
I don’t like to use “var” when I have to go to some method definition to find out what variable type “var” represents or by having to rely on visual studio intelli-popup or whatever that is called, for example this in not ok to me:
var someVaraible = SomeMethod();
I mean, what is the “SomeMethod” function supposed to return? Can you tell just by looking at the line of code? No you can’t, so that is why I avoid using “var” on those situations.
Why should I use implicit types (var) when it is possible?
Using implicit typing does NOT mean that the variable is not strongly-typed. It means that the compiler implies the type from the right-hand side of the statement.
var i = 1;
i
is defines as having type int
. It's exactly the same as saying int i = 1;
but the type is implied.
Similarly, the following code is a lot easier to read:
var pairs = new List<pair<int, IEnumerable<string>>>();
than if you had to type:
List<pair<int, IEnumerable<string>>> pairs = new List<pair<int, IEnumerable<string>>>();
and yet the results are exactly the same.
Why is implicit typing disallowed in non-local variable declarations?
The simple answer is because that's how Microsoft introduced the var keyword in the specification for .NET 3.0.
http://msdn.microsoft.com/en-us/library/bb384061.aspx
Implicitly-typed local variables must be initialized
var containsMethod = <XYZ>;
Tells the compiler - "hey, you, analyze the expression <XYZ>
and, whatever type you deduce for that, make that the type for my containsMethod
variable".
But in your case, you've not given it any expression to analyze. So you can't use an implicitly typed variable (var
), and you have to tell it what type containsMethod
is instead.
So:
MethodInfo containsMethod;
maybe.
Are implicitly-typed variables the way forward (C#)
Those are not generics, those are implicitly typed variables. This is really largely a matter of taste. There are places where you can overdo the use of var
and there are places where it's very clearly necessary (think anonymous types) so just find the place in the middle that suits your (and your team's) preference.
Implicitly typed local variables must be initialized: scope definition
have two point of return instead of one:
var results = //determine the result type here
try
{
var calc = (Type1)obj;
return calc.Function();
}
catch
{
var calc = (Type2)obj;
return calc.Function();
}
also
you should check if obj is of type Type1 before trying the cast to avoid exceptions.
Like this:
if (obj is Type1)
{
return (obj as Type1).Function();
}
else
{
return (obj as Type2).Function();
}
Furthermore
since you must have a return type that the two return types must conform to, you could potentially do this(but this is not recommended):
var result = //type of return type
try
{
var calc = (Type1)obj;
result = calc.Function();
}
catch
{
var calc = (Type2)obj;
result = calc.Function();
}
finally
{
return result;
}
ASP.NET - Implicitly-typed local variables must be initialized
When using var
, the compiler doesn't know what the type of directories
is unless you initialize while you declare it. You have to declare a type if you're initializing later.
string[] directories;
if (filePath == "")
{
directories = Directory.GetDirectories(filePath);
}
//etc
Related Topics
Unauthorised Webapi Call Returning Login Page Rather Than 401
What's the Difference Between System.Valuetuple and System.Tuple
Itextsharp Insert Text to an Existing PDF
Is It Considered Acceptable to Not Call Dispose() on a Tpl Task Object
Extension Methods Must Be Defined in a Non-Generic Static Class
Views in Separate Assemblies in ASP.NET MVC
How to Populate/Instantiate a C# Array with a Single Value
Linq Contains Case Insensitive
Opening New Window in Mvvm Wpf
Predefined Type 'System.Valuetuple'2' Is Not Defined or Imported
How to Get the Computer Name in .Net
Differencebetween a Mutable and Immutable String in C#
Unzip Files Programmatically in .Net