Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to initialise array of reference types?

By default, an array of reference types gets initialised with all references as null.

Is there any kind of syntax trick to initialise them with new default objects instead?

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();
    }
}
like image 462
GazTheDestroyer Avatar asked Sep 19 '12 09:09

GazTheDestroyer


4 Answers

Use LINQ:

 private Child[] _children = Enumerable
                                 .Range(1, 10)
                                 .Select(i => new Child())
                                 .ToArray();
like image 51
cuongle Avatar answered Oct 17 '22 04:10

cuongle


You could use object and collection initializers, though your version is probably terser and can be used as is for larger collections:

private Child[] _children = new Child[] { 
new Child(),
new Child(),
new Child(),
new Child(),
new Child(),
new Child(),
new Child(),
new Child(),
new Child()
};
like image 40
Oded Avatar answered Oct 17 '22 05:10

Oded


You could use Array.Fill method:

public static void Fill<T> (T[] array, T value);
public class Child
{
}

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

    public Parent()
    {
        Array.Fill(_children, new Child());
    }
}
like image 3
Beny Avatar answered Oct 17 '22 04:10

Beny


Even if your for loop looks worse, than the nice LINQ statement the runtime behavior of it will be much faster. E.g. a test with 20 Forms in an array is 0.7 (for loop) to 3.5 (LINQ) milliseconds

like image 2
Whuppa Avatar answered Oct 17 '22 03:10

Whuppa