It struck me as weird that any class that inherits from IEnumerable<T> doesn’t need to implement Add(T object), even though if you want to use collection initializers when initializing the class instance, you have to implement Add(T object).
Why this is so?
IEnumerable<T>is a read-only interface – it’s only meant to represent “a sequence”.Collection initializers require
Addin order to work, but they check that the type implementsIEnumerablefirst 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 implementIEnumerable<T>IIRC) and they don’t require a specificAddsignature as collection initializers can be used with different numbers of arguments. For example,Dictionary<TKey, TValue>hasAdd(TKey value, TValue value)so you can use:That means it can’t be restricted to (say)
IListwhich only has the single-argumnetAddmethod. It needs duck typing to some extent, but theIEnumerablerequirement is an attempt to make sure thatAddreally means “add an item to the collection” rather than something completely different. The compiler doesn’t use the fact that it implementsIEnumerable– it never callsGetEnumeratorwhen building the collection, for example.