Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable DateTime in C#

I have two questions related to DateTime assingments

DateTime? y = 1 == 1 ? null: DateTime.MaxValue;
DateTime? y = null; // assignment works as expected
  • Why the first assignment issues error of type conversion between null and DateTime?
  • Which is the preferred way for null assignments of DateTime? in c#.

    DateTime? x = default(DateTime?); //prints null on console
    
    DateTime? x = null;               // prints null on console
    
    DateTime? x = DateTime.MinValue;  //print 01/01/0001 
    
like image 500
vibhu Avatar asked May 13 '26 20:05

vibhu


1 Answers

The second statement DateTime? y = null; is only an assignment of null to a nullable object.

Whereas the first is a conditional assignment, which assigns some value for the true state and some other value for the false; Here you are using the conditional operator for evaluating the condition. according to MSDN first_expression (executes if true) and second_expression*(executes if false)* must be of same type or an implicit conversion must exist from one type to the other. In our case both are different so The simple solution is doing an explicit conversion as like this:

DateTime? y = 1 == 1 ?(DateTime?) null : DateTime.MaxValue;
like image 142
sujith karivelil Avatar answered May 15 '26 09:05

sujith karivelil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!