Why does this generate a compiler error:
class X { public void Add(string str) { Console.WriteLine(str); } }
static class Program
{
static void Main()
{
// error CS1922: Cannot initialize type 'X' with a collection initializer
// because it does not implement 'System.Collections.IEnumerable'
var x = new X { "string" };
}
}
but this doesn’t:
class X : IEnumerable
{
public void Add(string str) { Console.WriteLine(str); }
IEnumerator IEnumerable.GetEnumerator()
{
// Try to blow up horribly!
throw new NotImplementedException();
}
}
static class Program
{
static void Main()
{
// prints “string” and doesn’t throw
var x = new X { "string" };
}
}
What is the reason for restricting collection initializers — which are syntactic sugar for a call to an Add
method — to classes that implement an interface which doesn’t have an Add
method and which isn’t used?
foreach
. – DimorphismList<T>
, for example. – Nic