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
You cannot do that with int
.
And there is no code in System
or anywhere else that you can edit to achieve anything of that sort.
However, what you can do is define your own struct Integer
which will encapsulate an int
, and then define overloaded operators for it which will handle all the arithmetic in all the ways you want. You can even have it play an mp3 with Leonard Cohen's Hallelujah every time it detects and prevents a division by zero.
You will have to check if the denominator is zero on each and every division. That will save you the overhead of throwing an exception, which will probably be of the order of tens of thousands of times more expensive.
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.