jonathan
jonathan

Reputation: 41

how do i check if DateTime is null

if (string.IsNullOrEmpty(value)) is for string, but what is the code to check if Datetime is null?

    private DateTime? _ReleaseDate;

    public DateTime? ReleaseDate
    {
        get
        {
            return _ReleaseDate;
        }
        set
        {
            if ()
            {

            }
            else
            {
                _ReleaseDate = value;
            }
        }
    }

Upvotes: 1

Views: 4236

Answers (2)

ProgrammingLlama
ProgrammingLlama

Reputation: 38767

The ValueType? pattern is shorthand for Nullable<ValueType>. In your case you have Nullable<DateTime>.

As you can see from the docs, Nullable<ValueType> implements a HasValue property, so you can simply check it like so:

if (value.HasValue)
{

}
else
{

}

If you simply want to set a default value you can use the GetValueOrDefault method of Nullable<T> and do away with the if statement:

_ReleaseDate = value.GetValueOrDefault(DateTime.MinValue); // or whatever default value you want.

Upvotes: 5

TheGeneral
TheGeneral

Reputation: 81493

For nullbale types you can use HasValue or != null

However for your example (with the code shown), you have more options

public DateTime? ReleaseDate
{
    get
    {
        return _ReleaseDate;
    }
    set
    {
        // if value is null, then that's all good, _ReleaseDate will be null as well
        _ReleaseDate = value; 
    }
}

Or

public DateTime? ReleaseDate {get;set}

The only reason you would need to do something like below, is when you have some specific behaviour on null or otherwise

public DateTime? ReleaseDate
{
    get
    {
        return _ReleaseDate;
    }
    set
    {
        if (value.HasValue)
        {
            // has a value
        }
        else
        {
           // doesnt 
        }
    }
}

Upvotes: 2

Related Questions