how to make array of class objects using dynamic allocation in c#?

11,571

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}
}
Share:
11,571
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    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