Easy way to initialise array of reference types?
Asked Answered
C

4

7

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();
    }
}
Colicweed answered 19/9, 2012 at 9:56 Comment(2)
No, just the obvious ways to hide the loop (putting it in a helper method, etc.).Minuet
+1 for pointing out that you want a syntax trick, not what most people ask for - "can I do this without iterating the array?". However, I assume you want to maintain some sort of readability and actually be able to tell - at a glance - what the code does. =)Vitrescent
A
9

Use LINQ:

 private Child[] _children = Enumerable
                                 .Range(1, 10)
                                 .Select(i => new Child())
                                 .ToArray();
Angeloangelology answered 19/9, 2012 at 9:59 Comment(0)
C
3

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()
};
Crowl answered 19/9, 2012 at 10:0 Comment(0)
D
2

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

Devotee answered 19/3, 2014 at 14:44 Comment(1)
But often, we don't care. Still there is a good warning not to use LINQ for everything.Footless
U
2

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());
    }
}
Unmusical answered 11/11, 2021 at 23:27 Comment(1)
Note that this is .Net >= 5.0 only. It is also less useful for reference types since it fills the array with the same instance. However, useful to know it's an option, so thank you!Colicweed

© 2022 - 2024 — McMap. All rights reserved.