[c#] Check an integer value is Null in c#

I have got an integer value and i need to check if it is NULL or not. I got it using a null-coalescing operator

C#:

public int? Age;

if ((Age ?? 0)==0)
{
   // do somethig
}

Now i have to check in a older application where the declaration part is not in ternary. So, how to achieve this without the null-coalescing operator.

This question is related to c# .net

The answer is


Several things:

Age is not an integer - it is a nullable integer type. They are not the same. See the documentation for Nullable<T> on MSDN for details.

?? is the null coalesce operator, not the ternary operator (actually called the conditional operator).

To check if a nullable type has a value use HasValue, or check directly against null:

if(Age.HasValue)
{
   // Yay, it does!
}

if(Age == null)
{
   // It is null :(
}

Because int is a ValueType then you can use the following code:

if(Age == default(int) || Age == null)

or

if(Age.HasValue && Age != 0) or if (!Age.HasValue || Age == 0)

As stated above, ?? is the null coalescing operator. So the equivalent to

(Age ?? 0) == 0

without using the ?? operator is

(!Age.HasValue) || Age == 0

However, there is no version of .Net that has Nullable< T > but not ??, so your statement,

Now i have to check in a older application where the declaration part is not in ternary.

is doubly invalid.


Simply you can do this:

    public void CheckNull(int? item)
    {
        if (item != null)
        {
            //Do Something
        }

    }

There is already a correct answer from Adam, but you have another option to refactor your code:

if (Age.GetValueOrDefault() == 0)
{
    // it's null or 0
}