C# creating array of objects and initialize

Started by
5 comments, last by aavci 11 years, 4 months ago
hi,

i have some experience with c++. but when i tried to port my c++ program, i ran into the following problems.

in the attached file, you can see that vsc# does not like what i did.

i tried to create a class object 'World' array objects. in subsequent lines, i also tried to initialize them.

in c++, my codes would look like the following:

enum func {julia=0, mandelbrot};
struct world { GLdouble l, r, b, t;
func fname;
int maxIter;}

and to initialize, all i have to do is:

world O[2] = {{-1.6, 1.6, -1.0, 1.0, julia, maxIter}, // original world coord for julia set
{-0.5, 1.5, -1.25, 1.25,mandelbrot, maxIter}}; // and mandelbrot.

any idea?

any help will be appreciated.
Advertisement
Even in C++ you need to initialize the arrays in a constructor or other actual code. You can't assign to W like that in the class declaration.
Please don't ever post code as a screenshot again.

Telastyn is correct, the initialization code you have should be in a constructor. You can declare-only or declare-and-initialize in the class declaration, but you cannot initialize on its own. Think of the code in the class declaration scope as essentially executing at random, thus anything that depends on execution order is incorrect.

Also, "World O[0] = new World(blah blah blah);" would not be the right syntax in the constructor. Delete the first "World". That wouldn't be legal in C, either. O is already declared as an array of World, so O's elements are already declared as World objects.

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

hi

thanks for reply.

the reason that i posted a screenshot is to show the red wiggly lines under the errors, like in vs c#.

my c++ is running just fine. in c++, World is declared as a struct.

after your suggestions, i still get the errors. my code is now this:

World[] W;
W = new World[10];
World[] O;
O = new World[2];
O[0] = new World(-1.6, 1.6, -1.0, 1.0, function.julia, 500);
O[1] = new World(-0.5, 1.5, 01.25, 1.25, function.mandelbrot, 500);

what should i do now?

i googled and checked c# books, i thought i followed the suggestions, but it still generates errors.
You are trying to do the initialization-seperate-from-declaration in the class declaration which is not allowed. You probably should be doing something like this:
[source lang="csharp"]
World[] W = new World[10];
World[] O = new World[2] {
new World(-1.6, 1.6, -1.0, 1.0, function.julia, 500),
new World(-0.5, 1.5, 01.25, 1.25, function.mandelbrot, 500)
};
[/source]
Code not tested.
hi aavci,

it works, thanks
you are welcome, nickme.

This topic is closed to new replies.

Advertisement