Search code examples
c#collectionsenumerablecollection-initializer

IEnumerable Add method available only when using collection initializer


I'm planning to create an immutable class based on JObject.

One of the requirement is to directly deserialize object onto my new custom class, just like we do with JObject.

I've implemented GetEnumerator and Add method to enable collection initializer.

The code looks like below

public sealed class ImmutableJObject : IEnumerable
{
    readonly jObject jObeject;

    public ImmutableJObject(params object[] content)
    {
        this.jObject = new jObject(content);
    }

    public IEnumerator GetEnumerator()
    {
        return ((IEnumerable)jObject).GetEnumerator();
    }

    public void Add(string propertyName, JToken value)
    {
        this.jObject.Add(propertyName, value);
    }
}

Is it possible to make Add method accesible only when collection initializer is utilized?

Being immutable in nature, I don't want Add method to be public. But, it looks like it needs to be public in order to enable collection initializer

Thanks ahead!


Solution

  • No, there is no way to restrict the use of the Add method to a collection initializer. A collection initializer results in code that constructs the object, and then mutates it, so by definition a type cannot support a collection initializer (that is actually capable of initializing it, i.e. where the collection initializer doesn't just throw an exception) and be immutable.