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.
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.
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();
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();
}
You can use LINQ.
var a = (from x in Enumerable.Range(10) select new MyClass()).ToArray();
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.
I think i found easiest way
myclass = myclass.select(x=>new MYCLASS()).toArray();
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();