简体   繁体   中英

How to check if a double value is null in c#?

I have a method Test which accepts x as an optional parameter. X can accept positive,negative and zero value. I need to check if double is null then print the value of x else if double value is null then print its null. As default value of double is 0 and double can't be assigned to null, so how can i do this?

public static void Test([Optional] double x)
{
           //if x is not null print value of x

            //else print x is null
}
static void main()
{
    Test();-output expected x is null
    Test(5);-output expected x is 5
    Test(0);--output expected x is 0
    Test(-1);-output expected x is -1
}

[Optional] does not mean that if your arg is not present, it´s automaticylly null . Instead its an indicator that in case of an argument not being provided, it should get its default -value, which for double is not null , but 0 .A double cannot be null , unless you mean Nullable<double> or double? (which are synonyms). So in your case these two calls are completely identical:

Test();
Test(0);

If you want to distinguish between an arg being passed and being zero, you should use a Nullable<double> instead:

public static void Test([Optional] double? x)
{
    if(x == null)
    {
        Console.WriteLine("null");
    }
    else
    {
        Console.WriteLine("" + x);
    }
}

Now you can call it like Test which will evaluate to Test(null) .

public static void Test([Optional] double? x)
{

           if(x == null)
           {
                Console.WriteLine("null");
           }
           else
           {
                Console.WriteLine("" + x);
           }

}

Once upon a time, there was a person that was confused about the definition of types, and had, unbeknownst to him, chosen the wrong type to handle an input parameter. You see, he was expecting to pass a non existing value, called null into a method, however, the chosen datatype, did not allow for the value "null" to exist. In order to accomplish this task, a wise and helpful developer, simply showed him the error of his datatype choice, by writing a little more explicit pseudo code, that showed him the error of his ways. By coincidence, the pseudo code passed a compiler check. Funny how life works out.

nullable double => double? use double questionmark => ??

double? d1;
d1 = null;
double? d2;
d2 = 123.456;
double safe1 = d1 ?? 0.0;
double safe2 = d2 ?? 0.0;

Console.WriteLine($"d1={d1}, d2={d2}");
Console.WriteLine($"safe1={safe1}, safe2={safe2}");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM