how to make array of class objects using dynamic allocation in c#?
Solution 1
x[] myobjects = new x[10];
For an array you don't create a new one with parens 'new x()' An array is not dynamic though. You could use Array.Resize to alter it's size, but you're probably after a List
List<x> myobjects = new List<x>();
myobjects.add(new x());
Solution 2
You don't want to use an array but a list
List<SomeObject> myObjects = new List<SomeObject>();
FYI you were declaring the array wrong too.
It should be
x[] myobjects = new x[5];
Solution 3
x [] myobjects = new x[numberOfElements];
Creates an array of numberOfElements
references to objects of type x
. Initially those references are null. You have to create the objects x
independently and store references to them in Your array.
You can create an array and some objects whose references will end up in the array, using an initialisation list like:
x [] myobjects = new x[3] {new x(), new x(), new x()};
Solution 4
i Found that i can do this
x [] myobjects = new x[]{
new myobjects{//prop. goes here},
new myobjects{//prop. goes here}
}
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on June 04, 2022Comments
-
Admin about 2 years
i made a class named x; so i want to make array of it using dynamic allocation
x [] myobjects = new x();
but it gives me that error
Cannot implicitly convert type 'ObjAssig4.x' to 'ObjAssig4.x[]'
i know it's dump question but i am a beginner
thanks