开发者

Is there a way out of needing to use explicit cast or calling Nullable<T>.Value?

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 scenar开发者_StackOverflow中文版io 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?


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;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜