Sometimes compiler can not infer the variable type.For example if I define a string List like this:

Or string array List:

Obviously compiler infer type of the item.But if I do something like this:
public class Foo
: IEnumerable
{
List<string> _fooRecords = new List<string>();
public IEnumerator GetEnumerator()
{
return _fooRecords.GetEnumerator();
}
}
Or this:
public class Foo
: IEnumerable
{
List<string> _fooRecords = new List<string>();
public IEnumerator GetEnumerator()
{
foreach (var item in _fooRecords)
{
yield return item;
}
}
}
Compiler can not infer the variable type:

Then I thought maybe I need to implement IEnumerator interface and I did something like this:
public class FooEnumerator : IEnumerator
{
private List<string> recordsList;
private int index;
private string current;
public FooEnumerator(List<string> list)
{
recordsList = list;
}
public object Current
{
get { return current; }
}
public bool MoveNext()
{
if (index != recordsList.Count - 1)
{
current = recordsList[index];
index++;
return true;
}
return false;
}
public void Reset()
{
index = 0;
}
}
And use it like (in Foo Class):
public IEnumerator GetEnumerator()
{
return new FooEnumerator(_fooRecords);
}
But nothings changed.Now I'm wondering why compiler can't infer the loop variable type for custom types? Ofcourse Foo class was just an example,there are numbers of custom collections in .NET Framework.For example ControlCollection of Form Class:
When I loop through Form control's I can't do this:
foreach (var item in this.Controls)
{
item.Name = "bla bla bla.."; //error
}
I need to specify the type or I need to use OfType extension method:
foreach (Control item in this.Controls)
{
item.Name = "bla bla bla.."; // OK!
}
foreach (var item in this.Controls.OfType<Control>())
{
item.Name = "bla bla bla.."; // OK!
}
Now I'm just wondering what is the actual reason,compiler isn't smart enough? Or just can not make sure the returning type until the loop executes ?
IEnumerable<T>instead ofIEnumerable?