Search code examples
c#listinitialization

How can i initialize List of reference type with same elements that will use same constructor?


I want to initialize List<File> with exact size and all elements should be created using constructor with parameters.

Here's File class:

public class File
{
    public int Value;
    public File(int value)
    {
        Value = value;
    }
}

I cannot change this class.

I tried using Files = new List<File>(new File[filesCount]) but this way each element is null but atleast i got the size of List right. Then i used Files.Foreach(x => x = new File(0)) and as it was expected it didn't work as we can't change object that we got while iterating.

At the end of the day i want to have a List<File> where all items are Files and have Value of 0


Solution

  • You can use the System.Linq Enumerable class:

    var Files = Enumerable.Repeat(new File(0), filesCount).ToList();