49

I am very new in C# and I have a doubt.

In an application on which I am working I found something like it in the code:

if (!String.IsNullOrEmpty(u.nome))

This code simply check if the nome field of the u object is not an empty\null string.

Ok this is very clear for me, but what can I do to check it if a field is not a string but is DateTime object?

AndreaNobili
  • 38,251
  • 94
  • 277
  • 514

2 Answers2

126

If you declare a DateTime, then the default value is DateTime.MinValue, and hence you have to check it like this:

DateTime dat = new DateTime();

 if (dat==DateTime.MinValue)
 {
     //unassigned
 }

If the DateTime is nullable, well that's a different story:

 DateTime? dat = null;

 if (!dat.HasValue)
 {
     //unassigned
 }
Ajay2707
  • 5,624
  • 6
  • 38
  • 56
Fabian Bigler
  • 9,721
  • 6
  • 41
  • 64
20

DateTime is not standard nullable type. If you want assign null to DateTime type of variable, you have to use DateTime? type which supports null value.

If you only want test your variable to be set (e.g. variable holds other than default value), you can use keyword "default" like in following code:

if (dateTimeVariable == default(DateTime))
{
    //do work for dateTimeVariable == null situation
}
Jaroslav Kadlec
  • 2,447
  • 4
  • 31
  • 41