Reputation: 17186
I'm new to nullable types. I like them for adding a value that can mean "no set", but I don't like having to cast them back later on, or having to tack on the .Value.
Here's specifically my scenario in context of a wrapper class that implements one of my repository types:
public DateTime TimeCreated
{
get { return inner.TimeCreated.IsSet() ? inner.TimeCreated.GetValue() : DateTime.MaxValue; }
}
I'd like to change to using DateTime? but as I understand it, then when I access the property I have to use either (DateTime)TimeCreated or TimeCreated.Value and, for me, it kind of defeats the purpose of wrapping the type in the first place having to add verbosity to any code that accesses it.
Question: is there an easy workaround for this? Or am I missing some point, as I feel may be the case?
Upvotes: 1
Views: 236
Reputation: 10875
This doesn't really directly answer your question, but if this type of thing is common and important to you, it might be worthwhile to consider other options. For example, F# has a completely different mechanism for dealing such situations and "null" rather uncommon.
Upvotes: 1
Reputation: 27495
Casting from a Nullable<T>
to T is a narrowing conversion, as the new type cannot represent the value 'null'. Any time you have a narrowing conversion, it's good to make it explicit, to help remind the developer that it might fail.
On a side note, you don't need the cast if you use the null-coalescing operator, since this removes the opportunity for failure:
int? someValue = X;
int realValue = someValue ?? int.MaxValue;
Upvotes: 4