Ever since getting Resharper I’ve been a fan of using var inside methods wherever possible. So later if you pass in a different type the change cascades down through your code without having to change every int declaration to a double.
Which brings me to my question. I’m retrieving a list of DataListItems from a DataList
var daysWorked = dlResourcesAllocated.Items;
Then stepping through the List it returns
foreach (var d in daysWorked)
{
var c = d.FindControl("ucSomethingSomething"); //Doesn't compile d has no methods
}
And my d is suddenly cast to an Object that has no methods
foreach (DataListItem d in daysWorked)
{
var c = d.FindControl("ucSomethingSomething");
}
However works just fine.
I’m just curious how come “var” can’t figure out it’s a collection of DataListItem. Intellisense seems to know it.
I’m sure there’s a perfectly simple one liner explanation for this. The skeet dude is probably gonna show up and point out I shoulda paid better attention when reading C# in depth…
This is because
DataListItemCollectiononly implementsIEnumerable, notIEnumerable<DataListItem>, as it predates generics.Since it doesn’t implement
IEnumerable<T>, the runtime usesObjectin yourforeachloop unless you explicitly provide the type.By writing this:
The compiler sees that
daysWorkedimplementsIEnumerable, and rewrites this as:When using
foreachwithIEnumerable(non-generic), you are allowed to provide the type explicitly:Doing this effectively casts the results from the
IEnumerablefor you, providing the proper type in your loop.