Casting an object which could be null

Posted by DeeMac on Stack Overflow See other posts from Stack Overflow or by DeeMac
Published on 2012-06-28T14:16:16Z Indexed on 2012/06/30 15:16 UTC
Read the original article Hit count: 126

Filed under:
|
|
|
DateTime? testDate = (DateTime?)arrayOfObjects[dateObject];

Does that code look ok? I attempted to use the as operator but I got the 'non-nullable' error. What I'm trying to say is that the object I'm choosing from the array is either DateTime or a null DateTime but either can be assigned to testDate.

Doesn't feel right doing it this way, I think I'm missing something obvious.

EDIT: I suppose it's the same as the way I could've adapted the as in the following way:

DateTime? testDate = arrayOfObjects[dateObject] as DateTime?;

Is either line of code the best way of handling potential nulls?

© Stack Overflow or respective owner

Related posts about c#

Related posts about datetime