So I've got some code that passes around this anonymous object between methods:
var promo = new
{
Text = promo.Value,
StartDate = (startDate == null) ?
new Nullable<DateTime>() :
new Nullable<DateTime>(DateTime.Parse(startDate.Value)),
EndDate = (endDate == null) ?
new Nullable<DateTime>() :
new Nullable<DateTime>(DateTime.Parse(endDate.Value))
};
Methods that receive this anonymous object type declare its type as dynamic
:
private static bool IsPromoActive(dynamic promo)
{
return /* check StartDate, EndDate */
}
At run-time, however, if StartDate
or EndDate
are set to new Nullable<DateTime>(DateTime.Parse(...))
, a method that receives this dynamic
object (named promo
) performs this:
if (promo.StartDate.HasValue && promo.StartDate > DateTime.Today ||
promo.EndDate.HasValue && promo.EndDate < DateTime.Today)
{
return;
}
It throws an exception:
Server Error in '/' Application.
'System.DateTime' does not contain a definition for 'HasValue'
What's going on here? What don't I understand about Nullable
types and the dynamic
keyword?
This code worked fine before I changed I removed the struct
that previously stored Text
, StartDate
, and EndDate
and replaced it with an anonymous type and passed it around as dynamic
.