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 compiler replaces null comparisons with a call to HasValue , so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues. I would add to that "whichever is more consistent/follows an existing coding style."
DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.
Use model. myDate. HasValue. It will return true if date is not null otherwise false.
Is it possible to set datetime object to null in C#? DateTime is a Value Type like int, double etc. so there is no way to assigned a null value.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With