55

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
  • 40,955
  • 107
  • 324
  • 596
  • I think its quite simple, if u.Datefield!=null?u.Datefield:DateTime.MinValue; – Incredible Feb 20 '14 at 11:02
  • 1
    Almost identical to this one he/she asked this morning: http://stackoverflow.com/questions/21904138/how-to-check-if-a-field-is-not-null – laminatefish Feb 20 '14 at 11:06
  • 2
    Since you are new to C# and seem eager to learn. Read this, http://www.microsoft.com/en-us/download/confirmation.aspx?id=7029 and check 4.1.10 on Nullable types for your specific question here. – Aaron Palmer Feb 20 '14 at 11:12

2 Answers2

141

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,690
  • 6
  • 40
  • 58
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70
22

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,505
  • 4
  • 32
  • 43