Use int to test if below 0 . uint in c# wraps around to a huge number once it goes below 0, this is in all programming languages.
Asked
Active
Viewed 852 times
0
-
Not possible sadly – Sep 29 '18 at 04:42
-
3Why not check if your uint is bigger than the number you're subtracting before you subtract it? If it isn't, set your uint to 0. – ProgrammingLlama Sep 29 '18 at 05:22
-
1One of the most useful and most overlooked build options is Project > Properties > Build tab > Advanced button, "Check for arithmetic overflow/underflow". Ideal in the Debug configuration and ideally suited to remind you to write the code to stop underflow where necessary. – Hans Passant Sep 29 '18 at 10:35
2 Answers
4
You can do it like this
uint i = 0;
i = checked(i - 1);
This will throw System.OverflowException
. Though it will not stay zero, at least you will be sure that no overflow happened.

Yola
- 18,496
- 11
- 65
- 106
-2
I just use ordinary int instead of uint, and check if its < 0... problem solved

user366866
- 55
- 1
- 4
-
2Considering you are answering your own question (which generally isn't a problem), _why_ did you pick `uint` in the first place. Surely it was for the positive range. I feel this question-answer pair isn't useful – Sep 29 '18 at 04:35
-
-
...and if you decrement an `int` value of `-2,147,483,648` it suddenly wraps round to `2,147,483,647` and vice versa. These are all symptoms of how integer values are stored in binary – Sep 29 '18 at 04:41