Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return null in the method

Tags:

c#

null

double

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;
     } 
}

    `  
like image 904
Pae Avatar asked Oct 14 '16 12:10

Pae


People also ask

Is it good to return null in Java?

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.

Why is my method returning null?

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.

What happens if you return null?

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.

Can you pass null to a method?

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.


1 Answers

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))) {  
  ...
}
like image 170
Dmitry Bychenko Avatar answered Oct 26 '22 08:10

Dmitry Bychenko