Reputation:
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?
Upvotes: 3
Views: 5781
Reputation: 273439
Is either line of code the best way of handling potential nulls?
The second form will silently result in null
when the array contains something other than a DateTime. That seems a good reason to use the first.
To the basic question:
am I missing something or is this the typical (or at least an acceptable) approach
It is acceptable but a little obscure maybe, because it is 'hiding' an unboxing operation.
You could use:
DateTime? testDate = null;
if (arrayOfObjects[dateObject] != null)
testDate = (DateTime) arrayOfObjects[dateObject]; // no '?'
But that's verbose. And this particular problem doesn't lend itself well to the conditional operator (?:
)
So I would stick with your first version.
Upvotes: 4
Reputation: 2379
Try using Array.ConvertAll method. Below is roughly how it is implemented:
DateTime?[] dates = Array.ConvertAll<object, DateTime?>arrayOfObjects,DateTime);
Note: This is just a rough idea. you can correct it to suit your self.
Upvotes: -1
Reputation: 31097
A better approach would be to do something like:
if(arrayOfObjects[dateObject] != null && arrayOfObjects[dateObject] is DateTime)
{
DateTime testDate = (DateTime)arrayOfObjects[dateObject];
// logic here
}
or something like:
DateTime? testDate = null;
if(arrayOfObjects[dateObject] is DateTime)
{
testDate = (DateTime)arrayOfObjects[dateObject];
}
else if (arrayOfObjects[dateObject] is Nullable<DateTime>)
{
testDate = (Nullable<DateTime>)arrayOfObjects[dateObject];
}
Upvotes: 0
Reputation: 4143
DateTime? is a shorter form for another struct
Nullable<DateTime> {
bool HasValue;
DateTime Value;
}
You will never get this type from your DB, so the first line will never cast correctly. The database will provide you with a DateTime value stored in an object variable. Or a null (untyped).
DateTime is a struct, so "as" operator won't work for it. So, simply check for null as follows:
DateTime? testDate = arrayOfObjects[dateObject] == null ? (DateTime?) null : (DateTime)arrayOfObjects[dateObject];
Upvotes: 2