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();
    }
}
2
  • No, just the obvious ways to hide the loop (putting it in a helper method, etc.).
    – dtb
    Sep 19, 2012 at 9:58
  • 1
    +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. =)
    – J. Steen
    Sep 19, 2012 at 9:58

4 Answers 4

9

Use LINQ:

 private Child[] _children = Enumerable
                                 .Range(1, 10)
                                 .Select(i => new Child())
                                 .ToArray();
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()
};
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

1
  • But often, we don't care. Still there is a good warning not to use LINQ for everything.
    – Mr. Boy
    Jul 22, 2020 at 14:14
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());
    }
}
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! Nov 12, 2021 at 10:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.