Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.hasvalue vs datetime == null, which one is better and why [duplicate]

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.

like image 888
Aurora Avatar asked Jun 27 '16 15:06

Aurora


People also ask

Does HasValue check for NULL?

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."

Can a DateTime field be null?

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.

How do you check if a DateTime field is not null or empty?

Use model. myDate. HasValue. It will return true if date is not null otherwise false.

Can DateTime be null C #?

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.


2 Answers

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        
}
like image 169
sujith karivelil Avatar answered Nov 15 '22 06:11

sujith karivelil


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);
like image 36
Mong Zhu Avatar answered Nov 15 '22 06:11

Mong Zhu