How can I change the `DivideByZeroException` from throwing into handling?

后端 未结 2 1581
梦谈多话
梦谈多话 2021-01-26 11:31

I want to give int a similar behavior like float, i.e. to make it able to divide by 0 but I want it to return 0.
Furthermore, I want to ov

2条回答
  •  梦谈多话
    2021-01-26 12:14

    As others have said, you can't do that. You can't redefine math. About the best solution you could get is to have an extension method. Something like:

    public static int SafeDivision(this int nom, int denom)
    {
        return denom != 0 ? nom/denom : 0;
    }
    

    Which you could use like:

    Console.WriteLine(10.SafeDivision(0));    // prints 0
    Console.WriteLine(10.SafeDivision(2));    // prints 5
    

    Which is a bit fiddly to use...

    Or as @MikeNakis suggested in his answer, you can create your own struct with your own logic.

提交回复
热议问题