6

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.

1
  • If you have a struct, then you don't have to initialize every item, as they are already allocated with a default value. Commented Jun 12, 2010 at 9:55

6 Answers 6

6

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

It is better to use new MYCLASS[10] instead of Enumerable.Range(0,10) stackoverflow.com/questions/3028192/…
2
var a = Enumerable.Repeat(new MYCLASS(), 10).ToArray();

Comments

2

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

Comments

2

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.

Comments

1

You can use LINQ.

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

Comments

1

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

1 Comment

You should have updated your answer rather than providing a second one

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.