Consider this working code:
RadComboBox rcb = new RadComboBox(); // Telerik.Web.UI.RadComboBox
rcb.Items.Add(new RadComboBoxItem("One", "1"));
rcb.Items.Add(new RadComboBoxItem("Two", "2"));
rcb.Items.Add(new RadComboBoxItem("Three", "3"));
// check all items
foreach (RadComboBoxItem i in rcb.Items)
{
i.Checked = true;
}
If I replace the foreach loop with var, it does not compile:
RadComboBox rcb = new RadComboBox(); // Telerik.Web.UI.RadComboBox
rcb.Items.Add(new RadComboBoxItem("One", "1"));
rcb.Items.Add(new RadComboBoxItem("Two", "2"));
rcb.Items.Add(new RadComboBoxItem("Three", "3"));
// check all items
foreach (var i in rcb.Items)
{
i.Checked = true;
}
The error is:
'object' does not contain a definition for 'Checked' and no extension method 'Checked' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
So, I wonder, what are the conditions when you cannot use var?
Edit: Just to clarify, I wasn't simply asking "why doesn't this work"? Here's an example that could make the problem more obvious:
List<Object> stuff = new List<object>();
stuff.Add("one");
stuff.Add("two");
stuff.Add("three");
foreach (string s in stuff)
{
if (s.Length > 3)
// do something
}
Now if you change string s in stuff to var s in stuff, it obviously isn't going to compile. You can't just willy-nilly go and replace any type with var and expect it to compile. The error in my thinking that led me to propose the question in the first place was that I assumed that since rcb.Items is of type RadComboBoxItemCollection, that the enumerable type would be RadComboBoxItem, and this is not the case.
Unfortunately my example tainted the question by leading some of the answers down the "why does substituting a type with var not work?" path. Paulo actually answered with what I was looking for (others partially did too), which is why I have awarded it the best answer.