Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What advantages does using var have over the explicit type in C#? [duplicate]

Tags:

c#

var

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.

like image 817
Corey Ogburn Avatar asked Aug 06 '10 16:08

Corey Ogburn


3 Answers

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.

like image 178
Ben Robinson Avatar answered Sep 21 '22 07:09

Ben Robinson


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)

like image 45
Mike M. Avatar answered Sep 22 '22 07:09

Mike M.


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);
}
like image 38
JaredPar Avatar answered Sep 23 '22 07:09

JaredPar