Best way to handle Integer overflow in C#?

前端 未结 6 424
臣服心动
臣服心动 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 07:52

    Sometimes, the simplest way is the best way. I can't think a better way to write what you wrote, but you can short it to:

    int x = foo();
    
    if ((x * common) / common != x)
        Console.WriteLine("oh noes!");
    else
        Console.WriteLine("safe!");
    

    Note that I didn't remove the x variable because it'd be foolish to call the foo() three times.

提交回复
热议问题