Saif
Saif

Reputation: 31

comparing dates in c# taking null value into account

I am new to c#. I am comparing two dates where one is entered by user and the other one is sytem date time. i have the code working as it stands where the obstacle has occured is how to cater for null values. the basic code I have is:

if (mydate.ToShortDateString() != TodaysDate.ToShortDateString())

{
//Error Messaage
}

else
{
//do some code
}

Any feedback will be appreciated

Upvotes: 3

Views: 555

Answers (3)

code4life
code4life

Reputation: 15794

Use the ?? operator:

if ((mydate??DateTime.MinValue).ToShortDateString() != TodaysDate.ToShortDateString())
{
//Error Messaage
}

else
{
//do some code
}

Upvotes: 0

dcp
dcp

Reputation: 55444

You can declare mydate as DateTime?, then it can hold null values.

As to how to handle the error, it depends on whether having a null value for mydate is considered an error or not. If it's an error, you could do:

if (mydate == null || mydate.ToShortDateString() != TodaysDate.ToShortDateString()) {
    // error
}

If it's not an error condition, you could do:

if (mydate != null && mydate.ToShortDateString() != TodaysDate.ToShortDateString()) {
    // error
}

If you don't declare mydate as DateTime? but instead just declare it as DateTime, then you can check for DateTime.MinValue, like this (DateTime.MinValue is the default value for a DateTime variable):

if (mydate == DateTime.MinValue || mydate.ToShortDateString() != TodaysDate.ToShortDateString()) {
    // error
}

Upvotes: 0

Hans Olsson
Hans Olsson

Reputation: 55009

Why are you converting them to strings? Why not just compare the date portions of them as in date1.Date != date2.Date.

Upvotes: 2

Related Questions