Reputation: 26058
Is writing something like this kosher? Or are there problems that may arise?
private DateTime? getDate(object date)
{
return date != null ? Convert.ToDateTime(date) : (DateTime?)null;
}
I've seen a lot of questions asking a similar question, but the answer is always given an extension method that does the job of converting, I was wondering if I could skip that step and write like this, or is there some edge case I am not accounting for?
Also I'm using DateTime in the example, but I would think this could work for any nullable type.
Upvotes: 1
Views: 123
Reputation: 1595
Since the ?
is a type of Nullable<T>
, it is completely fine and 'kosher' as long as you are aware of the actual return type. It is as if you are writing the method as:
private Nullable<DateTime> getDate(object date)
{
...
}
As long as you are aware the below won't work because the return types will differ:
DateTime myDateTimeVariable = getdate(someObject);
because it's a type conversion problem.
You can see this for another explaination: Nullable DateTime?
Upvotes: 1