views:

86

answers:

6

Hello

For example

MYCLASS[] myclass = new MYCLASS[10];

Now myclass array is all null array but i want to have default constructed Array .I know that i can write loops for set default constructed but i am looking for more easy and simple way.

+2  A: 

There isn't an easier way. If you just don't like loops, you could use

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

which would give you an array with 4 elements of type MyClass, constructed with the default constructor.

Otherwise, you just have the option to use a loop.

If you don't want to write that loop every time you want to construct your array, you could create a helper-method, for example as an extension method:

 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();
    }
}

And then use it like this:

MyClass[] array = new MyClass[10];
array.ConstructArray();
Maximilian Mayerl
+5  A: 

If you don't want to write out the loop you could use Enumerable.Range instead:

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

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

MyClass[] a = new MyClass[10];
for (int i = 0; i < a.Length; ++i)
{
    a[i] = new MyClass();
}
Mark Byers
Benchmark can be found here: http://dotnetperls.com/initialize-array
Mikael Svenson
It is better to use new MYCLASS[10] instead of Enumerable.Range(0,10)http://stackoverflow.com/questions/3028192/how-can-i-create-array-of-my-class-with-default-constructor/3028257#3028257
Freshblood
+1  A: 

You can use LINQ.

var a = (from x in Enumerable.Range(10) select new MyClass()).ToArray();
TcKs
A: 

There isn't really a better way. You could do something like:

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;
}

then at least you only need:

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

This approach should at least avoid any reallocations, and can use the JIT array/length optimisation. The : class is to avoid use with value-types, as with value-types already initialize in this way; just new MyValueType[200] would be better.

Marc Gravell
+1  A: 

I think i found easiest way

myclass = myclass.select(x=>new MYCLASS()).toArray();
Freshblood
A: 

If we want to do all job in only one line code so this is best

MYCLASS[] myclass = (new MYCLASS[10]).Select(x => new MYCLASS()).ToArray();
Freshblood
You should have updated your answer rather than providing a second one
ChrisF