Sign in to follow this  

C# creating array of objects and initialize

Recommended Posts

nickme    253

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.

Share this post

Link to post
Share on other sites
capn_midnight    1707
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.

Share this post

Link to post
Share on other sites
nickme    253

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.

Share this post

Link to post
Share on other sites
aavci    137
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)
Code not tested. Edited by aavci

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this