How can I create an array of my class with a default constructor?

for example

MYCLASS[] myclass = new MYCLASS[10];

Now the myclass array is the entire null array, but I want Array to be constructed by default. I know that I can write loops for the default installation, but I'm looking for a simpler and easier way.

+5
source share
6 answers
var a = Enumerable.Repeat(new MYCLASS(), 10).ToArray();
+2
source

If you do not want to write out a loop, you can use : Enumerable.Range

MyClass[] a = Enumerable.Range(0, 10)
                        .Select(x => new MyClass())
                        .ToArray();

Note: it is significantly slower than the method you mentioned using the loop written here for clarity:

MyClass[] a = new MyClass[10];
for (int i = 0; i < a.Length; ++i)
{
    a[i] = new MyClass();
}
+6
source

. ,

MyClass[] array = new[] { new MyClass(), new MyClass(), new MyClass(), new MyClass() };

4 MyClass, .

.

, , , , :

 static class Extension
 {
    public static void ConstructArray<T>(this T[] objArray) where T : new()
    {
        for (int i = 0; i < objArray.Length; i++)
            objArray[i] = new T();
    }
}

:

MyClass[] array = new MyClass[10];
array.ConstructArray();
+2

. - :

public static T[] CreateArray<T>(int len) where T : class, new() {
    T[] arr = new T[len];
    for(int i = 0 ; i <arr.Length ; i++) { arr[i] = new T(); }
    return arr;
}

:

Foo[] data = CreateArray<Foo>(150);

JIT/length. : class , , ; new MyValueType[200] .

+2

LINQ.

var a = (from x in Enumerable.Range(10) select new MyClass()).ToArray();
+1

If we want to do all the work in only one line, that would be better

MYCLASS[] myclass = (new MYCLASS[10]).Select(x => new MYCLASS()).ToArray();
+1
source

All Articles