Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check an integer value is Null in c#

Tags:

c#

.net

People also ask

Can a number be null in C?

In c, besides pointers you cannot set c objects to NULL. You cannot cast NULL to other object since it encapsulates nothing. So you might want to set your struct variables to 0 instead of NULL.

What is the null value for int in C?

In C, a null pointer constant must be an integer literal with the value 0, or the same cast to type "pointer to void"1.


Nullable<T> (or ?) exposes a HasValue flag to denote if a value is set or the item is null.

Also, nullable types support ==:

if (Age == null)

The ?? is the null coalescing operator and doesn't result in a boolean expression, but a value returned:

int i = Age ?? 0;

So for your example:

if (age == null || age == 0)

Or:

if (age.GetValueOrDefault(0) == 0)

Or:

if ((age ?? 0) == 0)

Or ternary:

int i = age.HasValue ? age.Value : 0;

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 :(
}

Simply you can do this:

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

    }

Since C# version 9 you can do this:

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

  }

Or more readable:

  public void CheckNull(int? item)
  {
    if (item is not 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
}

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.


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)