0

Suppose the List/array

List<int> a = new List<int>(){1,2,3,4,5};
int []a = new int[]{1,2,3,4,5};

And I want to change the value at index 2, whats the correct way?

a[2]++; or a[2] = a[2]++;

Please explain the answer.

Shubham Tyagi
  • 798
  • 6
  • 21

2 Answers2

0

The correct way is the first one:

A[2]++;

The second one also works but it does more work than necessary. It is equivalent to the following code:

a[2] = a[2]; // useless
a[2]++;

The suffix ++ operator (as in x++) applies after the line in which it appears has finished executing. The prefix ++ operator (as in ++x) first modifies the element and then uses the value.

I suggest you read the documentation about the "increment operator":

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#increment-operator-

Gaston Simone
  • 113
  • 1
  • 5
  • 1
    "*The second one also works*" [Nope, it doesn't.](https://stackoverflow.com/q/6716189/87698) – Heinzi Nov 24 '21 at 15:41
0

The result of a[2] = a[2]++ will be a[2], in this case 3.

The postfix increment a[2]++ will change the value of a[2] after the line in which it appears has finished.

If you want to change the value, then a[2]++ or a[2] = ++a[2] are valid.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Carrivas
  • 51
  • 8