Is there an easy way within C# to check to see if a DateTime instance has been assigned a value or not?
The only way of having a variable which hasn't been assigned a value in C# is for it to be a local variable - in which case at compile-time you can tell that it isn't definitely assigned by trying to read from it :)
I suspect you really want Nullable<DateTime>
(or DateTime?
with the C# syntactic sugar) - make it null
to start with and then assign a normal DateTime
value (which will be converted appropriately). Then you can just compare with null
(or use the HasValue
property) to see whether a "real" value has been set.
DateTime is value type, so it can not never be null. If you think DateTime? ( Nullable ) you can use:
DateTime? something = GetDateTime();
bool isNull = (something == null);
bool isNull2 = !something.HasValue;
do you mean like so:
DateTime datetime = new DateTime();
if (datetime == DateTime.MinValue)
{
//unassigned
}
or you could use Nullable
DateTime? datetime = null;
if (!datetime.HasValue)
{
//unassigned
}
I generally prefer, where possible, to use the default value of value types to determine whether they've been set. This obviously isn't possible all the time, especially with ints - but for DateTimes, I think reserving the MinValue to signify that it hasn't been changed is fair enough. The benefit of this over nullables is that there's one less place where you'll get a null reference exception (and probably lots of places where you don't have to check for null before accessing it!)