Enhanced C#
Language of your choice: library documentation
|
Same as Nullable{T} except that it behaves like a normal type, i.e. (1) T is allowed to be a reference type and (2) you can nest them, as in Maybe{Maybe{int}}
.
More...
Same as Nullable{T} except that it behaves like a normal type, i.e. (1) T is allowed to be a reference type and (2) you can nest them, as in Maybe{Maybe{int}}
.
The name of this type comes from some functional programming languages which define a type such as data Maybe t = Nothing | Just t
.
This type exists primarily for generic code, since C# does not allow you to write a generic function that returns "T?" if T could be a class. Places where this type is used include the DictionaryExt.TryGetValue(key) extension method, and the ILexer<T>.NextToken() method. Both of these may not be able to return a value, but they cannot return T? because T could be a class (or even a Nullable-of-something).
There is an implicit conversion from T that returns new Maybe{T}(value)
, and from NoValue.Value that returns Maybe{T}.NoValue. Since C# doesn't allow us to define conversions to/from T?
, these conversions can be accomplished with the extension methods Maybe.AsNullable and Maybe.AsMaybe.
The Or method replicates the C# ??
operator.
Public fields | |
readonly T | _value |
readonly bool | _hasValue |
Properties | |
static Maybe< T > | NoValue [get] |
bool | HasValue [get] |
T | Value [get] |
Properties inherited from Loyc.IHasValue< out T > | |
T | Value [get] |
Public Member Functions | |
Maybe (T value) | |
T | Or (T defaultValue) |
Converts Maybe{T} to T, returning a default value if HasValue is false. More... | |
void | Then (Action< T > then) |
R | Then< R > (Func< T, R > then, Func< R > @else) |
R | Then< R > (Func< T, R > then, R defaultValue) |
Static Public Member Functions | |
static implicit | operator Maybe< T > (T value) |
static implicit | operator Maybe< T > (NoValue _) |
|
inline |
Converts Maybe{T} to T, returning a default value if HasValue is false.
This is equivalent to the ??
operator of T?
.