Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an element auto-instantiated array such as the int arrays of an user-defined type?

Tags:

arrays

c#

.net

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?

like image 417
CodeCamper Avatar asked Dec 11 '22 13:12

CodeCamper


2 Answers

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);
like image 57
mandaleeka Avatar answered Mar 23 '23 01:03

mandaleeka


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();      
}
like image 26
Simon Belanger Avatar answered Mar 23 '23 01:03

Simon Belanger