Upon declaring an int array such as:
int[] test = new int[5];
All of the elements of the array are automatically initialized to 0
. Is there anyway I can create a class that will auto-initialized when an array is created such as the int arrays?
For example:
MyClass[] test2 = new MyClass[5];
Will still require me to call the constructor; but with int
the constructor is magically called.
What code/operators of the int
class that allows this behavior?
The problem here is that MyClass is a reference type so the default value is null. Because you don't initialize the objects in the array, they are null. You could write a helper like:
T[] InitializeArray<T>(int length) where T : new()
{
T[] array = new T[length];
for (int i = 0; i < length; ++i)
{
array[i] = new T();
}
return array;
}
and then initialize your array:
MyClass[] something = InitializeArray<MyClass>(5);
The int
array isn't magically set to 0. Int
is a value type with a default value of 0 where as MyClass
is a reference type with a default value of null
.
If you want to create an array with everything initialize, you can use a fluent extension method:
public static T[] InitializeAll<T>(this T[] source) where T : new()
{
if(source != null)
{
for(var i = 0; i < source.Length; ++i)
{
source[i] = new T();
}
}
return source;
}
var test2 = new MyClass[5].InitializeAll();
Or mandaleeka solution, using a loop.
Edit: I'm reinstating my original solution as Guffa's comment need it for context
public static T[] CreateArray<T>(int size) where T : new()
{
return Enumerable.Repeat(new T(), size).ToArray();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With