6

i'd like to ask a question about controlling null value of a datetime.

if (mydatetime != null)

or

if(mydatetime.hasvalue)

which one is better, or proper and why?

thank you.

Aurora
  • 422
  • 1
  • 7
  • 21

2 Answers2

5

The First comparison with !=null is a valid comparison, whereas the second can be used only if the variable is declared as Nullable, Or in other words comparison with .HasValue can only be used when the DateTime variable is declared as Nullable

For example :

DateTime dateInput; 
// Will set the value dynamically
if (dateInput != null)
{ 
   // Is a valid comparison         
}
if (dateInput.HasValue)
{ 
   // Is not a valid comparison this time        
}

Where as

DateTime? dateInput; // nullable declaration
// Will set the value dynamically
if (dateInput != null)
{ 
   // Is a valid comparison         
}
if (dateInput.HasValue)
{ 
   // Is also valid comparison this time        
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
3

If you ask

if (mydatetime != null) 

you are checking whether the variable has been instantiated.

If it actually is not instantiated the following statement will give you a NullReferenceException

if(!mydatetime.hasvalue)

because you are trying to access a property of an object that is null

Only if you declare the DateTime as Nullable will it display the same behaviour.

Nullable<DateTime> mydatetime = null;

Console.WriteLine(mydatetime.HasValue);
Matthew
  • 1,630
  • 1
  • 14
  • 19
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76