Creating an array of instantiated class objects
Solution 1
I know that when you create an array of enum values, that array is already filled with instances of the enum which are set to their default value.
That happens because enums are based on integer types that are value types and can't be null
.
The easiest way to initialize an array of reference types is to loop as you have described (you can write very short syntax to do so using LINQ).
Solution 2
Try this:
MyClass[] myClassArray = Enumerable
.Range(0, 25)
.Select(i => new MyClass())
.ToArray();
This will create 25 instances of your class, and put them into an array.
Solution 3
Why not just encapsulate the annoying loop in a method?
public T[] CreateInstances<T>(int arrayLength) where T: new()
{
T[] result = new T[arrayLength];
for (int i=0; i<arrayLength; i++)
result[i] = new T();
return result;
}
Admin
Updated on June 14, 2022Comments
-
Admin almost 2 years
So I have a class (myClass) that I've created in my C# application. When working with arrays of this class, I have been thinking that it's rather annoying having to write a loop to fill an array of myClass objects. I know that when you create an array of enum values, that array is already filled with instances of the enum which are set to their default value.
I'm wondering if the same sort of functionality can be achieved with a class so that a call like:
myClass[] myClassArray = new myClass[25];
will result in an array of myClass objects which are just instances of the empty constructor for that class.
-
Oded over 12 yearsYou have not declared a loop, but a loop is still happening.
-
Sergey Kalinichenko over 12 years@Oded Absolutely, there is no way to avoid the loop. But you can at least get it out of your sight.
-
Nuffin over 12 yearsBeat me to it. I think that method should be static though... and it misses a
return result;
;) -
Admin over 12 yearsThis what I was afraid of. I just wasn't sure if I could overload something in my class to make things easier.
-
Oded over 12 years@marrithl2 - As you can see from other answers, you can write: 1. A method to do this. 2. An extension method. 3. A LINQ query to do this. Or, 4. As Henk posted - convert the class to a struct if possible.