Skip to content Skip to sidebar Skip to footer

How To Check If Datetime Object Was Not Assigned?

So, First of all. Code: I've got a class: public class Myobject { public string Code { get; set; } public DateTime? StartDate { get; set; } } And this is part of very si

Solution 1:

Try this:

if (mo.StartDate.GetValueOrDefault() != DateTime.MinValue) 
{
  // True - mo.StartDate has value
}
else
{
  // False - mo.StartDate doesn't have value
}

Solution 2:

should just be able to do

mo.StartDate!=null

instead of

mo.StartDate.Value!=null

Solution 3:

Running the simplest test with that class (as you presented it) yields false:

var mo = new Myobject();

        Console.WriteLine(mo.StartDate.HasValue);

Output is False.

I'd put a breakpoint on your constructor (if you have one), make sure nothing else is getting assigned, and walk through any methods called along the way to make sure there's nothing else setting the property that may not be immediately obvious...

Can you post more code, perhaps? There must be something in code not posted setting the property.

Solution 4:

.HasValue and ==null are the ways to check whether DateTime? is assigned a value or not. You are doing it right. There might be problem somewhere else that .HasValue returns true always.

Solution 5:

The way you're checking for null is fine, there must be something else that's setting the field's value.


To find what's setting the field you could right-click it then do find all references, then scan the list for any assignments.

Failing that, you could change it to an explicitly defined property temporarily and set a breakpoint within the set method, then execution will pause whenever the value is set and you can look up the call stack.

Post a Comment for "How To Check If Datetime Object Was Not Assigned?"