Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single line increment and return statement in C#

Having been playing around with C# the last few days and trying to take advantage of its "succinct" syntax I have tried to use the following trick.

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

Now the problem with this is that it returns the value prior to incrementing the number, so I tried...

_Array[(_LastIndex++)] = obj;

And yet the same behavior is occurring (Which has also got me a bit confused).

Could someone firstly explain why the second example (I understand why the first) doesn't work? And is there some way of accomplishing what I am trying to do?

like image 508
Maxim Gershkovich Avatar asked Dec 21 '22 17:12

Maxim Gershkovich


2 Answers

Surrounding the post-increment _LastIndex++ with parentheses doesn't separate it into a distinct operation, it just changes:

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

into:

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

If you want to increment before use, you need the pre-increment variant, as follows:

_Array[++_LastIndex] = obj;    // ++_LastIndex; _Array[_LastIndex] = obj;
like image 173
paxdiablo Avatar answered Jan 05 '23 01:01

paxdiablo


Have you tried _Array[++_LastIndex].

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

++LastIndex increments and returns the incremented value.

like image 22
digg Avatar answered Jan 05 '23 00:01

digg