开发者

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

开发者 https://www.devze.com 2023-01-02 00:47 出处:网络
i made a class named x; so i want to make array of it using dynamic allocation x [] myobjects = new x();

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


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());


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];


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()};


i Found that i can do this

x [] myobjects = new x[]{
   new myobjects{//prop. goes here},
   new myobjects{//prop. goes here}
}


The error

Cannot implicitly convert type 'ObjAssig4.x' to 'ObjAssig4.x[]'

is telling you that you are trying to declare a new x and assign it to your array. Instead, you need to declare a new array (which will also need a size):

x[] myobjects = new x[100];
0

精彩评论

暂无评论...
验证码 换一张
取 消