Question

I am trying to write a division method, which accepts 2 parameters.

public static decimal Divide(decimal divisor, decimal dividend)
{
    return dividend / divisor;
}

Now, if divisor is 0, we get cannot divide by zero error, which is okay.

What I would like to do is check if the divisor is 0 and if it is, convert it to 1. Is there way to do this with out having a lot of if statements in my method? I think a lot of if()s makes clutter. I know mathematically this should not be done, but I have other functionality for this.

For example:

if(divisor == 0)
{
    divisor = 1;
}
return dividend / divisor;

Can it be done without the if() statement?

Was it helpful?

Solution

You can do a conditional if statement like this. This is the same as IIF in VB.net

return dividend / ((divisor == 0) ? 1 : divisor);

Make sure you wrap your second half with () or you will get a divide error.

OTHER TIPS

By using the ?: operator

return (divisor == 0) ? dividend : dividend / divisor 

This is pretty much the same as an if statement, but it is cleaner.

return dividend / divisor == 0 ? 1 : divisor;

You could create your own type and overload the / operator to get the desired behaviour, if you really want. Implement the implicit conversion operators to avoid casting or type converting.

I don't think it would be a good idea, however, since it would add some runtime overhead; with the only benefit that you get some code that (arguably) looks a little cleaner.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top