Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Nullable<System.TimeSpan>' does not contain a definition for 'TotalMinutes'

Is there an elegant way around this error rather than checking .HasValue in the if() then adding the Value such as DateTimeUtcNow.Value?

// Compare nullable date time entity.End with utcnow but only compare up to minute precision
// for time.
//
if ((int)(entity.End - DateTime.UtcNow).TotalMinutes < 0) 
{
   // ASSERT: entity.End < UTCNow (i.e. 12/4/2012 3:56 PM < 12/4/2012 3:57 PM) 
}

Error: System.Nullable' does not contain a definition for 'TotalMinutes'

like image 237
genxgeek Avatar asked Feb 19 '23 06:02

genxgeek


2 Answers

Personally I'd write this as:

if (entity.End > DateTime.Now.AddMinutes(1))
{
    ...
}

That condition will be false if entity.End is null.

I often find that rather than one date/time from another and comparing that with a TimeSpan (or whatever type you're using), it's clearer to compute a lower-bound or upper-bound, and compare that with the variable date/time. It certainly works out cleanly in this case.

EDIT: Okay, now that the question's a little clearer, I'd write this as:

DateTime now = DateTime.UtcNow;
DateTime lowerBound = new DateTime(now.Year, now.Month, now.Hour, now.Minute,
                                   0, 0, DateTimeKind.Utc);
DateTime upperBound = now.AddMinutes(1);
if (entity.End >= lowerBound && entity.End < upperBound)
{
    ...
}

I suspect I may still have misunderstood though...

like image 176
Jon Skeet Avatar answered Feb 20 '23 21:02

Jon Skeet


One option is to create an extension method to access the value in a nullable and propagate nulls:

public static TOut? Select<T, TOut>(this T? nullable, Func<T, TOut> func) 
    where T : struct 
    where TOut : struct
{
    return nullable.HasValue ? (TOut?)func(nullable.Value) : null;
}

then you can do:

if ((entity.End - DateTime.UtcNow).Select(t => t.TotalMinutes) > 1)
{
}
like image 30
Lee Avatar answered Feb 20 '23 21:02

Lee