Jinna Baalu
Jinna Baalu

Reputation: 7809

Allow null DateTime? variable comparison with DateTime variable in C#

I have two variables of type DateTime and DateTime?

DateTime StartDateFromDb;
DateTime? StartDateFromFilter;

if(StartDateFromDb.Date == StartDateFromFilter.Date);

While comparing, .Date is not allowingfor StartDateFromFilter of type allow null

Thanks in advance

Upvotes: 0

Views: 1445

Answers (2)

M.S.
M.S.

Reputation: 4423

Use the Value property available as

  if(StartDateFromFilter.HasValue && StartDateFromDb.Date == StartDateFromFilter.Value.Date)

PS: Better to add a null value check. StartDateFromFilter must have a value.(HasValue is true when DateTime? type variable is not null)

Upvotes: 3

prabin badyakar
prabin badyakar

Reputation: 1726

For any nullable type , you can use value property. StartDateFromFilter.Value.Date

In your case , this should work fine

if(StartDateFromDb.Date == StartDateFromFilter.Value.Date)
//// in this case .Date is not allowingfor StartDateFromFilter

Upvotes: 2

Related Questions