IEnumerable<T>
is a read-only interface - it's only meant to represent "a sequence".
Collection initializers require Add
in order to work, but they check that the type implements IEnumerable
first to make sure it really is a collection type of some description. They don't require the generic form as that would be restrictive for some pre-2.0 code (in particular various UI collections don't implement IEnumerable<T>
IIRC) and they don't require a specific Add
signature as collection initializers can be used with different numbers of arguments. For example, Dictionary<TKey, TValue>
has Add(TKey value, TValue value)
so you can use:
var dictionary = new Dictionary<string, int>
{
{ "Jon", 33 },
{ "Tom", 6 }
};
That means it can't be restricted to (say) IList
which only has the single-argumnet Add
method. It needs duck typing to some extent, but the IEnumerable
requirement is an attempt to make sure that Add
really means "add an item to the collection" rather than something completely different. The compiler doesn't use the fact that it implements IEnumerable
- it never calls GetEnumerator
when building the collection, for example.