Best way to handle Integer overflow in C#?

前端 未结 6 422
臣服心动
臣服心动 2020-11-28 07:46

Handling integer overflow is a common task, but what\'s the best way to handle it in C#? Is there some syntactic sugar to make it simpler than with other languages? Or is th

6条回答
  •  借酒劲吻你
    2020-11-28 08:11

    So, I ran into this far after the fact, and it mostly answered my question, but for my particular case (in the event anyone else has the same requirements), I wanted anything that would overflow the positive value of a signed int to just settle at int.MaxValue:

    int x = int.MaxValue - 3;
    int someval = foo();
    
    try
    {
       x += someval;
    }
    
    catch (OverflowException)
    {
       x = int.MaxValue;
    }
    

提交回复
热议问题