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.
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.
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
}
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);