Use of var keyword in C#

Posted by kronoz on Stack Overflow See other posts from Stack Overflow or by kronoz
Published on 2008-09-03T11:29:57Z Indexed on 2010/03/11 18:29 UTC
Read the original article Hit count: 355

Filed under:
|
|
|
|

After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?

For example I rather lazily used var in questionable circumstances, e.g.:-

foreach(var item in someList) { // ... } // Type of 'item' not clear.
var something = someObject.SomeProperty; // Type of 'something' not clear.
var something = someMethod(); // Type of 'something' not clear.

More legitimate uses of var are as follows:-

var l = new List<string>(); // Obvious what l will be.
var s = new SomeClass(); // Obvious what s will be.

Interestingly LINQ seems to be a bit of a grey area, e.g.:-

var results = from r in dataContext.SomeTable
              select r; // Not *entirely clear* what results will be here.

It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.

It's even worse when it comes to LINQ to objects, e.g.:-

var results = from item in someList
              where item != 3
              select item;

This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.

There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type.

Edit - var does maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.

Related Question: http://stackoverflow.com/questions/633474/c-do-you-use-var

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET