Reputation:
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?
Upvotes: 5
Views: 25564
Reputation: 739
you can just compare to decimal.Zero
like somDecimalVar == decimal.Zero
Upvotes: 0
Reputation: 35797
By using the ?:
operator
return (divisor == 0) ? dividend : dividend / divisor
Upvotes: 13
Reputation: 21312
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.
Upvotes: 15
Reputation: 164341
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.
Upvotes: 0
Reputation: 70052
This is pretty much the same as an if statement, but it is cleaner.
return dividend / divisor == 0 ? 1 : divisor;
Upvotes: 1