Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple Array Question

Status
Not open for further replies.

mateobus

Programmer
Aug 20, 2007
28
0
0
US
I have seen this tactic used often in javascript, and it won't work in C#. Can someone explain why its not working as intended, i think the code should be self explanitory

Code:
MyObject[] objects= new MyObject[2];
int objIndex = 0;
objects[objIndex] = new MyObject();
objects[objIndex].someAttribute = "attr value";
objects[(objIndex++)] = new MyObject();
//Error occurs below that object hasn't been instantiated
objects[objIndex].someAttribute = "other attr value";

I am getting an error that the object at index 1 has not been instantiated. Basically, it is creating a new object at index 0, then incrementing the variable, and i want it to do the incrementing first. Is there a way to do this on one line?

Thanks in advance.
 
In case anyone wants to know, this works:

Code:
MyObject[] objects= new MyObject[2];
int objIndex = 0;
objects[objIndex] = new MyObject();
objects[objIndex].someAttribute = "attr value";
objects[++objIndex] = new MyObject();
//Error occurs below that object hasn't been instantiated
objects[objIndex].someAttribute = "other attr value";

++ before the var name makes sure that happens first.
 
Yes, var++, ++var and same with -- is basic knowledge of Ansi C/C++.
Your code is not very clear for me. I would change it like below. Notice that the objIndex++ action happens at the very last command of each object. So, at the last line the index will remain the same (because of the post increment) and the 'new MyObject();' will be saved at the next array location (the objIndex in now incremented by the previous ++).

Code:
MyObject[] objects= new MyObject[2];
int objIndex = 0;

objects[objIndex] = new MyObject();
objects[objIndex++].someAttribute = "attr value";

objects[objIndex] = new MyObject();
objects[objIndex++].someAttribute = "other attr value";
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top