Search code examples
c#object-initializerslist-initialization

C# List initialization using a list instead of Initializing List


My issue concerns the syntax of object initialization syntax in C#, specifically the syntax for initialize a List Property.

JSchema of the Newtonsoft .NET Schema library provide a Property named Enum that is a IList<JToken> and i want use object initialization to initialize an istance of a such JSchema class. To initialize this property i have to use a list o JToken called enumStrings.

Unfortunately the field Enum is readonly because it provides only the get, as you can see from JSchema.Enum.

//The list containing the values i want to use for initialization
List<JToken> enumString = ...

var schema = new JSchema
{
    Type = JSchemaType.Object,
    Properties =
    {
        { "EnumLabel", new JSchema
        {
            Type = JSchemaType.String,
            Enum = { listaenum } //ERROR: it expects a JToken not a List<JToken>
        } }
    }
};

I can't use the following solution too, because Enum property is read only:

Properties =
    {
        { "EnumLabel", new JSchema
        {
            Type = JSchemaType.String,
            Enum = new List<JToken>(enumStrings) //ERROR: a property without setter or inaccessible setter cannot be assigned to
        } }
    }

Any suggestion to accomplish this? The values are only contained in enumStrings and always change so they can be hard-coded in the object initializer.


Solution

  • Collection initializers call an Add method or extension method on the property value.

    Try creating an extension method:

    public static class CollectionInitializerExtensionMethods
    {
        public static void Add(this IList<JToken> list, IList<JToken> toAdd)
        {
             foreach (var a in toAdd)
             {
                 list.Add(a);
             }
        }
    }
    

    Failing that, just create the schema object, then find your property and call AddRange on it manually.