Duplicate
Use of var keyword in C#
C# – Do you use ‘var’?
Should I always favour implictly typed local variables in C# 3.0?
Would you prefer to write your code like this:
var myVar = new MyClass();
or
MyClass myVar = new MyClass();
I don’t object to use the var keyword in example above; however, in the code below I don’t like the usage of var.
var files = Files.GetFiles();
In this example it’s not obvious what type variable files is going to be.
What’s your preference for using the var keyword?
I tend to use ‘var’ in places where I, reading the sourcecode, can infer the type of the variable without having to navigate to other places in the sourcecode.
For example, any time I new up an object:
Or when calling a method in which the return type is clear:
Also, ‘var’ must be used in the case of anonymous types:
And I also use it with LINQ of course:
In the case above ‘q’ is of type IQueryable (assuming Customers is an enumeration of Customer objects).
Also ‘foreach’ statements as well – GREAT please to use ‘var’:
Other examples abound I’m sure – but these cover my most frequent use cases.