简体   繁体   中英

C# 4: Dynamic and Nullable<>

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 .

Great question. Two facts that you probably don't know:

  1. Dynamic behind the scenes is just object. That is, a "dynamic" variable is an "object" variable with a hint to the compiler that says "generate dynamic operations on this variable when it is used."

  2. There is no such thing as a boxed nullable. When you box an int? to object you get either a null object reference or a boxed int. The nullable wrapper around the int is thrown away.

Now it should be clear what is going on here. If promo is dynamic then promo.StartDate is dynamic. Which means that at runtime, it is object. Which means that if it is of value type, it is boxed. Which means that if it was nullable, it is now either a null reference or a boxed non-nullable value. Either way, that thing doesn't have a HasValue property. If you want to know whether it was in its value type form a nullable value type set to null, then check whether promo.StartDate is null or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM