Interviews - C# Corner

Sandeep Soni
Can DateTime be compared to null? Why or why not?
By Sandeep Soni in C# onOct 25 2018
  • Sandeep Soni
    Oct, 2018 25

    DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false.

    • 7
  • Sreekanth Reddy
    Oct, 2018 26

    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.

    • 5
  • Vinay
    Oct, 2018 30

    It can be compared but result will be False

    • 3
  • Vikas Agarwal
    Oct, 2018 26

    Yes, If declare DateTime variable as nullable like DateTime? then we can compare it with null.

    • 3
  • Kapil Gaur
    Oct, 2018 26

    And also to be noted if we compare with null it gives us false result because DateTime cannot understand what is null value and to which component of DateTime type it is actually being compared. So it is of no usage. I have given solution in my previous comment on how to deal with such situation.

    • 3
  • Kapil Gaur
    Oct, 2018 26

    DateTime is by default not a nullable type. So it can never store null value. Only if you declare DateTime nullable by notation DateTime? then it can hold null value. So I don't know what basically you want to perform. So suppose you want to do some assignment by checking whether the property has value or not for that you can use following.If you are using DateTime then DateTime dat = new DateTime();if (dat==DateTime.MinValue){//unassigned datetime}Or if you are using nullable DateTime then DateTime? dat = null;if (!dat.HasValue){//unassigned}So answer to your question simply is that DateTime can never hold null value so cannot be compared. But there are ways by which we can understand if that particular property is having intended DateTime value or not.

    • 3
  • Laxmidhar Sahoo
    Nov, 2018 1

    DateTime is Rererence type . So We can Instantiated it by the new operator.Generaly the null value is not accespted by the type variable.But we can make it nullable in the exampleDateTime? dt = null;var d = dt?.ToString();MessageBox.Show(d);

    • 2
  • Madan Bandari
    Oct, 2018 31

    NO

    • 2
  • siva b
    Mar, 2019 13

    DateTime? ff=null;if (ff==null){}

    • 1
  • Bhanuprasad Mitturi
    Nov, 2018 20

    DateTime is a value type (structure) and has default value 1/1/0001 12:00:00 AM. we can compare it with null but can not hold null as it is value type unless made it as nullable datatype.DateTime? today = DateTime.Now; today=null;

    • 1

Most Popular Companies

Most Popular Job Functions

MOST LIKED QUESTIONS