Re: DateTime Null

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



On Sun, 19 Oct 2008 14:43:30 -0700, shapper <mdmoura@xxxxxxxxx> wrote:

Sure ... Sorry. I tried:

DateTime c = database.Boxes.Max(b => b.CreatedAt ?? DateTime.UtcNow);

Which seemed logic to me but I get:
The null value cannot be assigned to a member with type
System.DateTime which is a non-nullable value type.

Ah. Yes, it would do that when the database is empty. But, if you move the coalescing operator out of the lambda expression, I think it should be okay:

DateTime c = database.Boxes.Max(b => b.CreatedAt) ?? DateTime.UtcNow;

Note that that's subtly different from what you did try:

I also tried:
DateTime c = database.Boxes.Max(b => b.CreatedAt).Value ??
DateTime.UtcNow;

You can only use nullable types with the coalescing operator. The Nullable<DateTime>.Value property is a non-nullable value type and so is an illegal operand for the operator.

Without a true concise-but-complete code sample, it's difficult to know for sure what will or won't work. But I'm pretty sure the above should solve your problem.

Pete
.