DateTime Null

S

shapper

Hello,

I have the following:

DateTime c = database.Posts.Max(b => b.CreatedAt).Value;

b.CreatedAt is of type "DateTime?"

The problem is when database.Posts is empty. I get an error:
Nullable object must have a value.

I understand that I get a null value but I am not able to apply ??
because it does not allow me.

How can I solve this?

Thanks,
Miguel
 
S

shapper

Can you be more explicit about what you mean by "it does not allow me"?  
You didn't post any code that tries to use the null coalescing operator  
(??).  There's not any particular reason why "it" (the compiler, I presume  
you mean) should not "allow" you to use it.

If you can post the code that you think should work but doesn't, we can  
help change that to code that does work.

Pete

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.

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

But this one does not even compile and I get:
Operator '??' cannot be applied to operands of type 'System.DateTime'
and 'System.DateTime

Thanks,
Miguel
 
S

shapper

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:


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

Thank You Pete. I didn't know that about value ... I though it would
still be a nullable DateTime.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

TimeSpan 2
How to... 1
SqlDateTime and DateTime 2
Converting DateTime? to itself throws invalidcastexception 3
DateTime range 11
Check if DateTime is valid 1
Class Properties Check 1
Null (?:) 5

Top