The code in the first case uses the collection initializer syntax. To be able to use the collection initializer syntax, a class must:
Collection Initializers:
- Implement the
IEnumerable
interface.
- Define an accessible
Add()
method. (as of C#6/VS2015, it may be an extension method)
So a class defined like so may use the syntax:
public class CollectionInitializable : IEnumerable
{
public void Add(int value) { ... }
public void Add(string key, int value) { ... }
public IEnumerator GetEnumerator() { ... }
}
var obj = new CollectionInitializable
{
1,
{ "two", 3 },
};
Not all objects are IEnumerable
or has an add method and therefore cannot use that syntax.
On the other hand, many objects define (settable) indexers. This is where the dicionary initializer is used. It might make sense to have indexers but not necessarily be IEnumerable
. With the dictionary initializer, you don't need to be IEnumerable
, you don't need an Add()
method, you only need an indexer.
Being able fully initialize an object in a single expression is generally useful (and in some contexts, a requirement). The dictionary initializer syntax makes it easier to do that without the steep requirements of using collection initializers.