Easy way to initialize an array of reference types?

By default, an array of reference types is initialized with all references as null.

Is there any syntax trick to initialize them with new default objects?

eg,

public class Child
{
}

public class Parent
{
    private Child[] _children = new Child[10];

    public Parent()
    {
        //any way to negate the need for this?
        for (int n = 0; n < _children.Length; n++)
           _children[n] = new Child();
    }
}
+5
source share
3 answers

Use LINQ:

 private Child[] _children = Enumerable
                                 .Range(1, 10)
                                 .Select(i => new Child())
                                 .ToArray();
+6
source

You can use collection objects and initializers , although your version is probably a term and can be used as for large collections:

private Child[] _children = new Child[] { 
new Child(),
new Child(),
new Child(),
new Child(),
new Child(),
new Child(),
new Child(),
new Child(),
new Child()
};
+3
source

Even if your for loop looks worse than a good LINQ statement, runtime behavior will be much faster. For instance. test with 20 forms in an array is 0.7 (for a loop) to 3.5 (LINQ) milliseconds

0
source

All Articles