tags:

views:

331

answers:

4

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?

+2  A: 

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

return dividend / divisor == 0 ? 1 : divisor;
Brandon
this is not cleaner than an If statement
Peter Gfader
+11  A: 

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.

Jason Heine
You don't need two set of parentheses do you? return dividend / (divisor == 0 ? 1 : divisor); should do the trick
Brian Rasmussen
No, I had an additional set you can do it like this as well: return dividend / (divisor == 0 ? 1 : divisor);
Jason Heine
But you do need the () wrapping the value of the result, other wise you still get the divide by zero error
Jason Heine
@Brian - no, you don't need the two sets, you are correct. On the flip side though I sometimes find Jason's approach more readable.
Alexander Kahoun
This is what I look for. Much thanks.
If in doubt, add parentheses.
Sprintstar
+9  A: 

By using ?: operator

return (divisor == 0) ? divident : divident / divisor
Jakub Šturc
+1 for pointing out that a division by 1 is unnecessary and just return the divident.
Michael Stum
This good too, but I like other one for further expanding purpose. I give +1 for your help.
A: 

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.

driis