Search code examples
c#typeinitializer

Instantiate a List inside of type initializer


Say I have a struct like so

public struct MyStruct
{
     string StructConfig { get; set; }
     List<string> Details { get; set; }

     public MyStruct
     {
         Details = new List<string>();
     }
}

And I instantiate this struct using:

MyStruct s = new MyStruct() 
{
    StructConfig = "Some config details"
}

I'm wondering how I could add a foreach loop that will add the details into the Details property, rather than doing:

MyStruct s = new MyStruct() 
{
    StructConfig = "Some config details"
}
s.Details = new List<string>();
foreach (var detail in someArray)
    s.Details.Add(detail);

Is this even possible? Am I dreaming of code-luxury?


Solution

  • You can do it like this:

    MyStruct s = new MyStruct() 
    {
        StructConfig = "Some config details",
        Details = new List<string>(someArray)
    }
    

    This works because List<T> supports initialization from IEnumerable<T> through this constructor.

    If you need to do additional preparations on the elements of someArray, you could use LINQ and add a Select. The example below adds single quotes around each element:

    Details = new List<string>(someArray.Select(s => string.Format("'{0}'", s)))