views:

405

answers:

8

It seems that more and more C# code I read uses the var type identifier:

foreach (var itemChange in ItemChanges)
{
   //... 
}

instead of explicitly stating the type:

foreach (ItemChange itemChange in ItemChanges)
{
   //... 
}

even when the type is known.

I am still using the latter explicit version just because I think someone reading it later will more quickly understand which type a variable is than if you use var.

But is there any technical reason to use one or the other?

+9  A: 

No, just readability.

Jorge Córdoba
I like this answer. Short and sweet.
RCIX
+19  A: 

There is no technical reason. If the type cannot be inferred at compile time then the code will not compile.

You are right in stating there are instances where it may be better to use an explicit type for readabilty, e.g.

var obj = SomeMethod(); // what's the type? you'd have to inspect SomeMethod()
SomeClass obj = SomeMethod(); // the type is obvious

but other instances where using var makes perfect sense, e.g.

var obj = new SomeClass(); // the type is obvious
SomeClass obj = new SomeClass(); // the duplication of type is unnecessary
AdamRalph
But (a) that just proves that `SomeMethod` is badly named, not that the type information is useful, and (b) why do you care about the concrete type anyway? I see a lot of answers to the `var` debate that assume that concrete type information aids readability without citing any evidence that it is so. Users of dynamic and functional languages would tend to disagree strongly with the assertion that inline type information is a good thing.
Greg Beech
I understand where you are coming from, howevera) you may not have control over the name of `SomeMethod`b) I don't particularly care, this is just a readability issue, some people may prefer to be able to know the type of the variable as they are reading subsequent codec) 'Users of dynamic and functional languages' - fair enough. I also do some IronPython coding and I can understand this context. however, this is a C# question
AdamRalph
+2  A: 

No. Use var where it improves readability and vice versa.

Anders Fjeldstad
+2  A: 

var is a C# 3.x+ feature, isn't it? without using that, your code is more compatible with other versions too.

And there is lots of interesting questions in SO, when you search "var C#"

S.Mark
It's actually a C# 3 feature, but still will work fine if you are targeting .Net 2.0
Phil Nash
Well, var is implemented in .Net 2.0 as a compiler trick, we use it occasionally in our .Net2.0 application.
Russ C
Thanks Phil Nash, You're right, Corrected.
S.Mark
+3  A: 

In general no technical reason. Readability - in either direction - is the only real factor.

However, one small caveat is that var will infer the static type of the variable. If you want a sub or super class type you'll need to do the casting yourself. In the case of a foreach, as in your example, you can usually get downcasting performed for you "for free" just by declaring your loop variable with the subclass type.

The classic example is iterating over an XML NodeList that you know is a list of XmlElement, but Nodelist is typed as a collection of XmlNodes. Of course you can use a cast or an as to get back the type you want, but that would seem to defeat the purpose of using type inference :-)

Of course, the compiler will let you know about this as soon as you try to use a member of the node that is only available to XmlElement - so it's still not strictly a technical difference.


Another thing that is a little annoying is that if you use a tool like Resharper, it's very aggressive about suggesting you use var in every possible situation. It's particularly annoying when it recommends you change, for example, an int declaration into a var!

However, unless you turn that feature off, you'll get less "noise" from Resharper the more you use var.

Phil Nash
+3  A: 

The only technical reason I know of is that you can perform implicit casts without var, e.g.

int i = 5;
double a = i; // implicit cast with explicit types

but here I much prefer var as it makes the cast explicit; while I don't care so much about the types I do care when I'm performing a representation changing type conversion:

var a = (double)i; // explicit cast with implicit types

But really the general reason is readability, as you said. The question you need to ask yourself is why you think the exact concrete type is important for readability? Do you always write Linq queries calling out the concrete type, e.g.

from ItemChange itemChange in ItemChanges

// instead of

from itemChange in ItemChanges

Similarly, do you always call out the type arguments to generic methods instead of using type inference, e.g.

ItemChanges.Select<ItemChange, ItemChange>((ItemChange itemChange) => ...);

// instead of

ItemChanges.Select(itemChange => ...);

Or are you happy to let the compiler do some work for you and let it work out the types, at the 'expense' of not having the type information explicitly stated?

If you're happy with type inference in linq and generic methods, then you've already made the decision that you're OK with not having types explicitly spelled out everywhere, and you probably haven't found your code to be any less readable as a result (in fact, you've probably found quite the opposite). So using var is just another step down the same path that you're already on.

Greg Beech
The Explicit Casting can be important in certain situations, for example if the Enumerator of a Collection returns "object" instead of the exact type. I think SPListItemCollection is such an example, but I think this applies to all Non-Generic-Collections.
Michael Stum
@Michael - agreed. I should have been more clear about the difference between representation changing and representation preserving casts (the ones I prefer to spell out explicitly with a cast operator are the representation changing ones). Yes, I think using the type name is clearer than a cast for representation preserving type coercions though.
Greg Beech
+3  A: 

var is a C# 3.0 feature only mandatory in anonymous type


Because following code

var v = new { Amount = 108, Message = "Hello" };

dynamically create a new anonymous type, var usage is mandatory. For example, var is particulatilly usefull in Linq where type are often created dynamically.


In any other situations, it's only a matter of taste for final application (it's resolved during compilation). But for code readers, I think 'var' is less informative that type itself.

MuiBienCarlota
A: 

There is no technical reason to use var, other than anonymous types, in any given state of the program.

However, using var allows the program to change without you needing to edit it. Given

public int SomeMethod(){}
public List<T> SomeOtherMethod<T>(T parameter);

then

var x = SomeMethod();
var y = SomeOtherMethod(x);

Will work (and y will be List<int>). If you had used

int x = SomeMethod();
List<int> y = SomeOtherMethod(x);

then if SomeMethod() were changed to return long, then you'd have to change the definition of y.

I've seen this kind of thing propagate throughout a program, requiring hundreds of changes. The particular case was changing data access code to return ReadOnlyCollection<T> rather than List<T>. There were so many code changes required, that I changed all explicit mentions of List<T> to var, and the code will never need to change again.

John Saunders