In your comparison between IEnumerable<int>
and IEnumerable<double>
you don't need to worry - if you pass the wrong type your code won't compile anyway.
There's no concern about type-safety, as var
is not dynamic. It's just compiler magic and any type unsafe calls you make will get caught.
Var
is absolutely needed for Linq:
var anonEnumeration =
from post in AllPosts()
where post.Date > oldDate
let author = GetAuthor( post.AuthorId )
select new {
PostName = post.Name,
post.Date,
AuthorName = author.Name
};
Now look at anonEnumeration in intellisense and it will appear something like IEnumerable<'a>
foreach( var item in anonEnumeration )
{
//VS knows the type
item.PostName; //you'll get intellisense here
//you still have type safety
item.ItemId; //will throw a compiler exception
}
The C# compiler is pretty clever - anon types generated separately will have the same generated type if their properties match.
Outside of that, as long as you have intellisense it makes good sense to use var
anywhere the context is clear.
//less typing, this is good
var myList = new List<UnreasonablyLongClassName>();
//also good - I can't be mistaken on type
var anotherList = GetAllOfSomeItem();
//but not here - probably best to leave single value types declared
var decimalNum = 123.456m;