0

Today im struggling with vectors, and im having problems with this. I have to invert the Y vector value but everytime i compile , Compiler complains about:

Syntax error ',' expected

 vector = new Vector3((float) ((-256 + ((iD & 7) * 0x40)) + 0x20), (float) ((-512 + ((iD / 8) * 0x40)) + 0x20), -200f) {
   Y = -vector.Y;  //error shows here at the semicolon
 }; 

1 Answers1

2

You're using object initializer syntax.

The compiler is correct.

You would place a comma there, instead of the semicolon, if you were to initialize more than one property. The comma is also legal even after the last property being initialized, but a semicolon is not legal.

So either of the following two is OK:

vector = new Vector3((float) ((-256 + ((iD & 7) * 0x40)) + 0x20), (float) ((-512 + ((iD / 8) * 0x40)) + 0x20), -200f) {
   Y = vector.Y
 }; 

vector = new Vector3((float) ((-256 + ((iD & 7) * 0x40)) + 0x20), (float) ((-512 + ((iD / 8) * 0x40)) + 0x20), -200f) {
   Y = vector.Y,
 }; 

Having said that, this will only satisfy the compiler. What are you really trying to do?

Please note that at the point where you read vector.Y, the vector variable has not yet been given a new value, so you're reading the old value.

Basically, the code is doing this:

var temp = = new Vector3((float) ((-256 + ((iD & 7) * 0x40)) + 0x20), (float) ((-512 + ((iD / 8) * 0x40)) + 0x20), -200f);
temp.Y = vector.Y;
vector = temp;

Why aren't you simply assigning that through the constructor instead?

vector = new Vector3((float) ((-256 + ((iD & 7) * 0x40)) + 0x20), vector.Y, -200f);
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • I wasn't aware that you could place a comma after the last property in an initializer. Thanks for the info! – dub stylee Jun 01 '15 at 21:20
  • It was allowed in order to make it easier for generated code to avoid having to deal with *not* placing a comma after the last value. It's legal in array and collection initializers as well. – Lasse V. Karlsen Jun 01 '15 at 21:25
  • Thanks about that, ive not noticed that. Also i have other question. Do i have to ask in a new question? – PerikiyoXD Jun 01 '15 at 21:56