Search code examples
c#listinstantiation

C# Instantiate IList object from a class and set local properties in one line


Hey wonderful stackoverflowers, I'm having some trouble with the IList object that is part of a class. It will later be serialized into JSON where the requirement is that it will produce an array with key value pairs inside of the customfield_10304 object.

Being used to working with Dictionaries for the similar purpose I'm trial-and-erroring away at doing something similar with an IList but failing.

            public class Customfield
            {
                public string self { get; set; }
                public string value { get; set; }
                public string id { get; set; }
            }
            public class RequestFieldValues
            {
                public IList<Customfield> customfield_10304 { get; set; }
            }

/* NOTE: This is how I THINK it should work in my mind, but it is throwing errors */
var customfield_10304 = new IList<string> { {value = "test", id = 0} } 

What's a good way to approach this? Please guide me into the most appropriate solution.

Thank you in advance


Solution

  • Are you trying to achieve something like this?

            new RequestFieldValues()
                .customfield_10304 = new List<Customfield>
                {
                    new Customfield{id ="id1", self = "Sefd1", value = "value1"},
                    new Customfield{id ="id2", self = "Sefd2", value = "value2"}
                };