tags:

views:

144

answers:

9

Possible Duplicates:
What’s the point of the var keyword?
Use of var keyword in C#

I understand how IEnumerable<...> for a datatype can make the code a little less readable or how nested generics can seem a little daunting. But aside from code readability, are there advantages to using var instead of the explicit type? It seems like by using the explicit type, you'd better convey what the variable is capable of because you know what it is.

If it's a workplace coding standard, I use it for the sake of teamwork. In my own projects however, I prefer to avoid the user of var.

+1  A: 

It produces no meaningful change in the emitted IL. It is merely a code style preference.

I, for one, like it, especially when dealing with types that have long, generic, almost unreadable names such as Dictionary<string, IQueryable<TValue1, TValue2>>[].

kbrimington
+2  A: 

I like it, especially in unit tests, because as the code evolves I only have to fix up the right-hand side of the declaration/assignment. Obviously I also have to update to reflect the changes in usage, but at the point of declaration I only have to make one change.

tvanfosson
This is the number one reason I `var` the heck out of my code.
Matthew Whited
A: 

The var is just a syntactic sugar. It is always known at compile time what type the variable is. There are no other advantages of using the var keyword.

Markos
Well, there are *some* other advantages. For example, being able to store off a reference to an instance of an anonymous type and still be able to reference the properties. (i.e. the result of a LINQ query using a Select clause to create ad-hoc objects)
Kirk Woll
+1  A: 

Using var as the iterator variable for a foreach block is more type safe than explicit type names. For example

class Item {
  public string Name; 
}
foreach ( Item x in col ) {
  Console.WriteLine(x.Name);
}

This code could compile without warnings and still cause a runtime casting error. This is because the foreach loop works with both IEnumerable and IEnumerable<T>. The former returns values typed as object and the C# compiler just does the casting to Item under the hood for you. Hence it's unsafe and can lead to runtime errors because an IEnumerable can contain objects of any type.

On the other hand the following code will only do one of the following

  1. Not compile because x is typed to object or another type which does not have a Name field / property
  2. Compile and be guaranteed to not have a runtime cast error while enumerating.

The type of 'x' will be object in the case of IEnumerable and T in the case of IEnumerable<T>. No casting is done by the compiler.

foreach ( var x in col ) {
  Console.WriteLine(x.Name);
}
JaredPar
`object` does not contain field `Name`. Sure that works?
Alexander
Problem #1: If `var x` resolves to `object`, you cannot access the `Name` property. You must still cast.
Anthony Pegram
@AnthonyPegram I came to same conclusion be wasn't *positive*
Alexander
@xander, @Anthony the point I'm trying to make is that there are only 2 outcomes with the use of `var` 1) compile = no runtime cast issue or 2) will not compile
JaredPar
Gotcha, your not saying it won't give a runtime error, just the cast is not necessary at compile-time with regards to 1st case...
Alexander
It would if his colleciton (which isn't shown) is of type `IEnumerable<Item>`
Matthew Whited
@xander correct.
JaredPar
@Matthew re-read the answer...
Alexander
@xander, If you look at the code blocks there is no assignment for the `col` variable. So you have no idea what type of variable it is. It could very well be `List<Item> : IEnumerable<Item>` or `ItemCollection : IEnumerable`.
Matthew Whited
@Matthew your still not seeing it? "Vaya con dios..."
Alexander
A: 

There aren't any real differences. Some people suggest using the explicit type because it can make maintaining the code easier. However, people that push for var have the stance that "if we use var, we are forced to use good naming conventions".

Of course if you use vars with the intention of having good naming conventions and that breaks down, it's more painful down the road. (IMO)

Mike M.
In my opinion, good coding conventions are more important when using 'var' than good naming conventions. Anything declared 'var' is in the current method scope. So long as methods are fairly concise (as they should be), it shouldn't be terribly hard to figure out what the variable is referencing.
Daniel Pratt
A: 

Besides the readability aspect you mentioned, 'var' also has the benefit of reducing the probability that a trivial code change will break other parts of your code. If you rename a type, for example. Or if you switch to a different type that is mostly compatible with the former type (e.g. changing from Foo[] to IEnumerable) you have much less work to do to get your code back to a compilable state.

Daniel Pratt
+2  A: 

The point of var is to allow anonymous types, without it they would not be possible and that is the reason it exists. All other uses I consider to be lazy coding.

Ben Robinson
+1  A: 
public IAwesome { string Whatever { get; } }
public SoCool : IAwesome { public string Whatever { get; } }

public HeyHey
{
    public SoCool GetSoCool() { return new SoCool(); }

    public void Processy()
    {
        var blech = GetSoCool();
        IAwesome ohYeah = GetSoCool();
        // Now blech != ohYeah, so var is blech and ohYeah is IAwesome.
    }
}
Jimmy Hoffa
+1 because "blech != ohYeah, so var is blech and ohYeah is IAwesome" made me smile
jloubert
A: 

You can abstract away the mental complexity of the technicalities to focus purely on the problem domain from your model. you have to make sure your variables are named meaningfully tho.

DaveDev