I'm trying to make converter which converting metrics to imperials. Also i'm doing unit test for it. If i pass negative value, the method supposed to return null. Is it possible to return null from the method which returns double.
public double mgToGrain(double mg)
{
double grain = mg * myValues["mgTograin"];
return grain;
if (mg < 0) {
return null;
}
}
`
Returning Null is Bad Practice The FirstOrDefault method silently returns null if no order is found in the database. There are a couple of problems here: Callers of GetOrder method must implement null reference checking to avoid getting a NullReferenceException when accessing Order class members.
The problem appears when Get is invoked on a cache which doesn't contain the item with specified key value. In that case, Get just returns the default value for the item type T – in reference types that means null. It is obvious that the client must guard from receiving null result back from the method call.
Returning null Creates More Work A function that returns a null reference achieves neither goal. Returning null is like throwing a time bomb into the software. Other code must a guard against null with if and else statements. These extra statements add more complexity to the software.
You can pass NULL as a function parameter only if the specific parameter is a pointer. The only practical way is with a pointer for a parameter. However, you can also use a void type for parameters, and then check for null, if not check and cast into ordinary or required type.
A possible alternative to double?
in case you have to stick to double
is double.NaN
(Not a Number):
public double mgToGrain(double mg) {
if (mg < 0)
return double.NaN;
else
return mg * myValues["mgTograin"];
}
...
double x = ...
if (double.IsNaN(mgToGrain(x))) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With