locked
How to check if double variable is blank (null) or 0 (zero). RRS feed

  • Question

  • User-1024101449 posted

    Hi,

    I want to check if variable has blank or 0 (zero).

    for example,

    double X = 0 or null;

    if x is blank (means null) or 0 (zero)

    {

     // blank or zero

    }

    else

    {

    //has value 

    }

    Wednesday, September 6, 2017 9:51 AM

Answers

  • User-1509636757 posted

    Double or double is a value type and you cannot directly assign null to it. That also means it cannot have a null value. To allow this, you have to define it as nullable. For more read you should refer to Nullable Types (C# Programming Guide) | Microsoft Docs

    To answer your question, I suggest you use nullable double type for X and then you will be able to check for null. Here is one example:

    double? x = null;
    if (null == x)
    {
        //-- this means x is null
    }
    else if (x.GetValueOrDefault() == 0)
    {
        //-- this means x is either null or 0 value
    }
    else
    {
        //-- this means x is neither null nor 0, it has some value other than 0
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 6, 2017 10:11 AM