Increment and return operation in a single line in C #

Playing with C # the last few days and trying to use my β€œshort” syntax, I tried to use the following trick.

Int32 _LastIndex = -1; T[] _Array; _Array[_LastIndex++] = obj; 

Now the problem is that it returns the value before the number increases, so I tried ...

 _Array[(_LastIndex++)] = obj; 

And yet the same behavior happens (which also confused me a bit).

Can someone first explain why the second example (I understand why the first) does not work? And is there a way to accomplish what I'm trying to do?

+4
source share
3 answers

The surrounding post-increment _LastIndex++ with parentheses does not separate it into a separate operation, it just changes:

 _Array[_LastIndex++] = obj; // _Array[_LastIndex] = obj; _LastIndex++; 

in

 _Array[(_LastIndex++)] = obj; // _Array[(_LastIndex)] = obj; _LastIndex++; 

If you want to increase it before use, you will need the pre-increment option as follows:

 _Array[++_LastIndex] = obj; // ++_LastIndex; _Array[_LastIndex] = obj; 
+5
source

Have you tried _Array[++_LastIndex] .

LastIndex++ increments the value, but returns the old value.

++LastIndex increments and returns an extra value.

+4
source

Do you want to:

 _Array[++_LastIndex] = obj; 

This is called pre-increment, which means that the increment occurs before the value is used. The brackets are used to change the priority, without necessarily changing the order of evaluation. In addition, parentheses did not affect priority in this case.

+2
source

Source: https://habr.com/ru/post/1342237/


All Articles