Skip to content

Suggestion: remove/weaken the IEnumerable requirement for collection initializers #266

@SolalPirelli

Description

@SolalPirelli

C# specification §7.6.10.3, Collection initializers:

The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or a compile-time error occurs.

This restriction is explained in an old blog post by Mads Torgersen: it ensures that collection initializers cannot be used on types whose Add method does not add an element to a collection, but does things like computing a sum.

However, as discussed in a CodePlex issue, there are a few use cases where the collection initializer syntax is desirable on objects that can't/shouldn't implement IEnumerable.

Additionally, collection initializers can already be used on immutable collections if they provide a constructor, since they're likely to both implement IEnumerable and have an Add method, but this obviously doesn't work properly.

Therefore, I suggest one of the following:

  • Lift the restriction entirely. Allow collection initializers on any object with an Add method.
    The simplest option. I do not have evidence for this, but I very much doubt that people actually try to use collection initializers on types that are not thought of as collections.
  • Keep the restriction, but also allow types to use an attribute indicating that they want to support collection initializers, as suggested by user 'supercat' in the original discussion.
    The safest option, ensuring that types won't get collection initializers if they don't want them.
  • Add many attributes to let collection initializers adapt to more patterns, such as immutable types or builders, as suggested by Jon Skeet (!) in the original discussion.
    The most complex option, which would probably fit more in a general "make C# more friendly to DSLs" feature.

Another idea (which is orthogonal to these suggestions) is to add an attribute that disables collection initializers, even on types implementing IEnumerable.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions