Struct Maybe<T>
- Namespace
- Existential
- Assembly
- Existential.Net.dll
Represents a value of type T that may or may not exist. Using Maybe<T>
helps to avoid null references in a safe and expressive manner, by encapsulating an optional value in a
type-safe way and allowing operations to be applied to it in ways that
don't require a value to be present.
The Maybe<T> struct provides properties and methods for dealing with the encapsulated optional value:
- Exists: Indicates whether the Maybe<T> contains a value.
- ToMaybe: Converts a nullable value to a Maybe<T>.
- Match, DoEither, IfExists: Execute different actions depending on whether the Maybe<T> contains a value or not.
- TryGetValue: Tries to get the value of the Maybe<T>, returning a boolean indicating success or failure.
- Map, Apply, Select, Bind, SelectMany: Transform the value inside the Maybe<T>, if it exists.
- Where: Filters the value inside the Maybe<T> based on a predicate.
- GetValueOr, GetValueOrMaybe, GetValueOrThrow: Retrieve the value inside the Maybe<T>, with different strategies for when it doesn't exist.
public readonly struct Maybe<T> : IEquatable<Maybe<T>>
Type Parameters
TThe type of the nullable value that is to be wrapped. The value may or may not exist.
- Implements
-
System.IEquatable<Maybe<T>>
- Inherited Members
-
System.Object.Equals(System.Object, System.Object)System.Object.GetType()System.Object.ReferenceEquals(System.Object, System.Object)
- Extension Methods
Remarks
Maybe<T> is a monadic optional type, based on an example by Yacoub Massad . It's defined as a struct because structs themselves cannot be null.
Additional support for using Maybe<T> is provided by the classes: Maybe, MaybeExtensions, MaybeReferenceTypeExtensions, MaybeValueTypeExtensions, and ObjectExtensions.
Properties
Empty
Gets an empty instance of Maybe<T>.
public static readonly Maybe<T> Empty { get; }
Property Value
Remarks
This property is used to represent a missing or non-existent value in computations. It's equivalent to default(Maybe<T>).
Exists
Gets a value indicating whether this Maybe<T> instance has a value.
public readonly bool Exists { get; }
Property Value
- System.Boolean
Trueif this instance has a value; otherwise,false.
Methods
Apply<TResult>(Func<T, TResult>)
Applies the specified conversion function to the current instance of Maybe{T}.
public readonly Maybe<TResult> Apply<TResult>(Func<T, TResult> inConvert)
Parameters
inConvertSystem.Func<T, TResult>The conversion function to apply to the current instance.
Returns
- Maybe<TResult>
A new instance of Maybe<T> that is the result of applying the conversion function to the current instance if it exists; otherwise, the default value of Maybe<T>.
Type Parameters
TResultThe type of the result of the conversion function.
Remarks
Equivalent to Map/Select; this is effectively an alias for comfort.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if the System.Func<T, TResult>
inConvertis null. Although this might be seen as contrary to the intentions of Maybe<T>, if no System.Func<T, TResult> is provided it's considered better to fail fast than to conceal the absence of an intended action by failing silently.- System.Exception
It's possible that the System.Func<T, TResult>
inConvertmay throw an exception when invoked.
Apply<TResult>(Func<T, Maybe<TResult>>)
Applies the specified conversion function to the current instance of Maybe<T> if it exists.
public readonly Maybe<TResult> Apply<TResult>(Func<T, Maybe<TResult>> inConvert)
Parameters
inConvertSystem.Func<T, Maybe<TResult>>The conversion function to apply to the current instance.
Returns
- Maybe<TResult>
A new instance of Maybe<T> that is the result of applying the conversion function to the current instance if it exists; otherwise, the default value of Maybe<T>.
Type Parameters
TResultThe type of the result of the conversion function.
Remarks
This method is a required part of the implementation of a Maybe monad. It can be used for chaining operations that change the underlying value or its type while preserving the "maybe" semantics, and is therefore useful in scenarios where you want to perform a series of transformations on a value that may or may not exist, while preserving the information about the existence of the value throughout the chain of transformations.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if the System.Func<T, TResult>
inConvertis null (where U is a Maybe<T>). Although this might be seen as contrary to the intentions of Maybe<T>, if no System.Func<T, TResult> is provided it's considered better to fail fast than to conceal the absence of an intended action by failing silently.- System.Exception
It's possible that the System.Func<T, TResult>
inConvertmay throw an exception when invoked (where U is a Maybe<T>).
Bind<TResult>(Func<T, Maybe<TResult>>)
Applies the specified conversion function to the current instance of Maybe{T}.
public readonly Maybe<TResult> Bind<TResult>(Func<T, Maybe<TResult>> inConvert)
Parameters
inConvertSystem.Func<T, Maybe<TResult>>The conversion function to apply to the current instance.
Returns
- Maybe<TResult>
A new instance of Maybe<T> that is the result of applying the conversion function to the current instance if it exists; otherwise, the default value of Maybe<T>.
Type Parameters
TResultThe type of the result of the conversion function.
Remarks
A required method of a monad. Here, it's an alias of Apply<TResult>(Func<T, Maybe<TResult>>) because Apply is thought to be more readable.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if the System.Func<T, TResult>
inConvertis null (where U is a Maybe<T>). Although this might be seen as contrary to the intentions of Maybe<T>, if no System.Func<T, TResult> is provided it's considered better to fail fast than to conceal the absence of an intended action by failing silently.- System.Exception
It's possible that the System.Func<T, TResult>
inConvertmay throw an exception when invoked (where U is a Maybe<T>).
DoEither(Action<T>, Action)
Applies one of the provided actions depending on whether the value exists.
public readonly void DoEither(Action<T> inSome, Action inNone)
Parameters
inSomeSystem.Action<T>The action to be executed if the Maybe instance contains a value.
inNoneSystem.ActionThe action to be executed if the Maybe instance does not contain a value.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if either the System.Action<T>
inSomeor the System.ActioninNoneis null. Although this might be seen as contrary to the intentions of Maybe<T>, if no System.Action<T> or System.Action is provided it's considered better to fail fast than to conceal the absence of an intended action by failing silently.- System.Exception
It's possible that either the System.Action<T>s
inSomeor the System.ActioninNonemay throw an exception when invoked.
DoEither<TResult>(Func<T, TResult>, Func<TResult>)
Applies one of two provided functions depending on whether the value exists.
public readonly Maybe<TResult> DoEither<TResult>(Func<T, TResult> inSome, Func<TResult> inNone)
Parameters
inSomeSystem.Func<T, TResult>A function to execute if the Maybe instance contains a value. This function takes the existing value as a parameter.
inNoneSystem.Func<TResult>A function to execute if the Maybe instance does not contain a value. This function takes no parameters.
Returns
- Maybe<TResult>
A new Maybe instance containing the result of the executed function.
Type Parameters
TResultThe type of the result returned by the functions.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if either the System.Func<T, TResult>
inSomeor the System.Func<TResult>inNoneis null. Although this might be seen as contrary to the intentions of Maybe<T>, if no System.Func<T, TResult> or System.Func<TResult> is provided it's considered better to fail fast than to conceal the absence of an intended action by failing silently.- System.Exception
It's possible that either the System.Func<T, TResult>s
inSomeor the System.Func<TResult>inNonemay throw an exception when invoked.
Equals(Maybe<T>)
public readonly bool Equals(Maybe<T> other)
Parameters
Returns
- System.Boolean
true if the current Maybe<T> object is equal to the
otherparameter; otherwise, false.
Equals(Object)
Indicates whether this instance and a specified object are equal.
public override readonly bool Equals(object obj)
Parameters
objSystem.ObjectThe object to compare with the current instance.
Returns
- System.Boolean
true if
objand this instance are the same type and represent the same value; otherwise, false.
GetHashCode()
Returns the hash code for this instance.
public override readonly int GetHashCode()
Returns
- System.Int32
The hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. If the Maybe instance exists, it returns the hash code of the underlying value. If the Maybe instance does not exist, it returns zero.
GetValueOr(T)
Retrieves the value contained in the Maybe<T> structure, or returns the provided default value if the Maybe<T> does not contain a value.
public readonly T GetValueOr(T inDefaultValue)
Parameters
inDefaultValueTThe value to return if the Maybe<T> does not contain a value. This value must not be null.
Returns
- T
The value contained in the Maybe<T> structure if it exists, otherwise the provided default value.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if the object
inDefaultValueis null, as a default value of null would invalidate the purpose of using Maybe<T>.
GetValueOr(Func<T>)
Gets the value contained in the Maybe<T> structure, or computes a default value using the provided
factory function (inDefaultValueFactory) if the Maybe<T> structure does not
contain a value. The factory method allows for lazy evaluation, meaning the alternative value is only generated
when needed.
public readonly T GetValueOr(Func<T> inDefaultValueFactory)
Parameters
inDefaultValueFactorySystem.Func<T>A factory function to compute a default value when the Maybe<T> structure does not contain a value.
Returns
- T
The value contained in the Maybe structure, or the computed default value.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if the System.Func<TResult>
inDefaultValueFactoryis null, as a non-existent default value factory would invalidate the purpose of using Maybe<T>.- System.Exception
It's possible that the System.Func<TResult>
inDefaultValueFactorymay throw an exception when invoked.
GetValueOrMaybe(Maybe<T>)
Gets the value of the current Maybe<T> instance if it exists, otherwise returns the provided
alternative value inAlternativeValue.
public readonly Maybe<T> GetValueOrMaybe(Maybe<T> inAlternativeValue)
Parameters
inAlternativeValueMaybe<T>The alternative Maybe<T> value to return if the current Maybe<T> instance does not exist.
Returns
- Maybe<T>
The value of the current Maybe<T> instance if it exists, otherwise the provided alternative value,
inAlternativeValue.
Exceptions
- System.ArgumentException
An System.ArgumentException will be thrown if the Maybe<T>
inAlternativeValuedoesn't have a value that exists, as a non-existent default value would invalidate the purpose of using Maybe<T>.
GetValueOrMaybe(Func<Maybe<T>>)
Gets the value of the current Maybe<T> object if it exists; otherwise, generates a new
Maybe<T> object using the provided factory function, inAlternativeValueFactory.
The factory method allows for lazy evaluation, meaning the alternative value is only generated when needed.
public readonly Maybe<T> GetValueOrMaybe(Func<Maybe<T>> inAlternativeValueFactory)
Parameters
Returns
- Maybe<T>
The current Maybe<T> object if it exists; otherwise, a new Maybe<T> object produced by the
inAlternativeValueFactoryfunction.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if the System.Func<TResult>
inAlternativeValueFactory(where U is of type Maybe<T>) is null, as a non-existent default value factory would invalidate the purpose of using Maybe<T>.- System.Exception
It's possible that the System.Func<TResult>
inAlternativeValueFactory{where U is of type Maybe<T>} may throw an exception when invoked.
GetValueOrThrow(String)
Retrieves the value if it exists, otherwise throws an System.InvalidOperationException.
public readonly T GetValueOrThrow(string inErrorMessage)
Parameters
inErrorMessageSystem.StringThe error message to include in the exception if no value exists.
Returns
- T
The existing value, of type T.
Exceptions
- System.InvalidOperationException
Thrown if no value exists.
IfExists(Action<T>)
Applies an action if the Maybe instance contains a value.
public readonly void IfExists(Action<T> inSome)
Parameters
inSomeSystem.Action<T>The action to apply if a value exists.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if the System.Action<T>
inSomeis null. Although this might be seen as contrary to the intentions of Maybe<T>, if no System.Action is provided it's considered better to fail fast than to conceal the absence of an intended action by failing silently.- System.Exception
It's possible that the System.Action<T>
inSomemay throw an exception when invoked.
Map<TResult>(Func<T, TResult>)
Transforms the value contained in the Maybe instance using the provided conversion function.
public readonly Maybe<TResult> Map<TResult>(Func<T, TResult> inConvert)
Parameters
inConvertSystem.Func<T, TResult>A function that transforms the contained value to a new value.
Returns
- Maybe<TResult>
A new Maybe instance containing the transformed value, or an empty Maybe if the original Maybe was empty.
Type Parameters
TResultThe type of the result produced by the conversion function.
Remarks
Equivalent to Apply/Select; this is effectively an alias for comfort.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if the System.Func<T, TResult>
inConvertis null. Although this might be seen as contrary to the intentions of Maybe<T>, if no System.Func<T, TResult> is provided it's considered better to fail fast than to conceal the absence of an intended action by failing silently.- System.Exception
It's possible that the System.Func<T, TResult>
inConvertmay throw an exception when invoked.
Match(Action<T>, Action)
Applies different actions depending on whether the Maybe instance contains a value.
public readonly void Match(Action<T> inSome, Action inNone)
Parameters
inSomeSystem.Action<T>The action to apply if a value exists.
inNoneSystem.ActionThe action to apply if no value exists.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if either the System.Action<T>
inSomeor the System.ActioninNoneis null. Although this might be seen as contrary to the intentions of Maybe<T>, if no System.Action<T> or System.Action is provided it's considered better to fail fast than to conceal the absence of an intended action by failing silently.- System.Exception
It's possible that either the System.Action<T>s
inSomeor the System.ActioninNonemay throw an exception when invoked.
Match<TResult>(Func<T, TResult>, Func<TResult>)
Applies different functions depending on whether the value exists.
public readonly Maybe<TResult> Match<TResult>(Func<T, TResult> inSome, Func<TResult> inNone)
Parameters
inSomeSystem.Func<T, TResult>The function to apply if a value exists.
inNoneSystem.Func<TResult>The function to apply if no value exists.
Returns
- Maybe<TResult>
The result of the function that was applied.
Type Parameters
TResultThe type of the result.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if either the System.Func<T, TResult>
inSomeor the System.Func<TResult>inNoneis null. Although this might be seen as contrary to the intentions of Maybe<T>, if no System.Func<T, TResult> or System.Func<TResult> is provided it's considered better to fail fast than to conceal the absence of an intended action by failing silently.- System.Exception
It's possible that either the System.Func<T, TResult>s
inSomeor the System.Func<TResult>inNonemay throw an exception when invoked.
Select<TResult>(Func<T, TResult>)
Applies the specified conversion function to the current instance of Maybe{T}.
public readonly Maybe<TResult> Select<TResult>(Func<T, TResult> inConvert)
Parameters
inConvertSystem.Func<T, TResult>The conversion function to apply to the current instance.
Returns
- Maybe<TResult>
A new instance of Maybe<T> that is the result of applying the conversion function to the current instance if it exists; otherwise, the default value of Maybe<T>.
Type Parameters
TResultThe type of the result of the conversion function.
Remarks
Equivalent to Apply/Map. Required for Linq compatibility.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if the System.Func<T, TResult>
inConvertis null. Although this might be seen as contrary to the intentions of Maybe<T>, if no System.Func<T, TResult> is provided it's considered better to fail fast than to conceal the absence of an intended action by failing silently.- System.Exception
It's possible that the System.Func<T, TResult>
inConvertmay throw an exception when invoked.
SelectMany<T2, TResult>(Func<T, Maybe<T2>>, Func<T, T2, TResult>)
Allows Linq queries to be written that reference multiple properties of the type
T underlying Maybe<T>.
public readonly Maybe<TResult> SelectMany<T2, TResult>(Func<T, Maybe<T2>> inConvert, Func<T, T2, TResult> inFinalSelect)
Parameters
inConvertSystem.Func<T, Maybe<T2>>A function that converts
Tto an intermediate type.inFinalSelectSystem.Func<T, T2, TResult>A function that produces a result using the original value and any value of the intermediate type.
Returns
- Maybe<TResult>
A container representing the result of applying both operations.
Type Parameters
T2The type of the intermediate result.
TResultThe type of the final result.
Remarks
Unlikely to be used directly, but required to support Linq usage.
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if the System.Func<T, TResult>
inConvertis null (where U is a Maybe<T>); or if the System.Func<T1, T2, TResult>inFinalSelectis null. Although this might be seen as contrary to the intentions of Maybe<T>, if no System.Func<T, TResult> or System.Func<T1, T2, TResult> is provided it's considered better to fail fast than to conceal the absence of an intended action by failing silently.- System.Exception
It's possible that either the System.Func<T, TResult>
inConvert(where U is a Maybe<T>), or the System.Func<T1, T2, TResult>inFinalSelectmay throw an exception when invoked.
ToMaybe(T)
Converts the given value of type T to a Maybe<T> instance.
public readonly Maybe<T> ToMaybe(T inValue)
Parameters
inValueTThe value to be wrapped in a Maybe{T}.
Returns
Remarks
This method is useful when you want to explicitly convert a value to a Maybe{T} type. It's required by the Framework Design Guidelines as an alternate for the implicit operator.
ToMaybe(Maybe<T>)
Returns the provided Maybe<T> structure unmodified, in order to prevent it being accidentally double-wrapped as a Maybe<Maybe<T>>.
public readonly Maybe<T> ToMaybe(Maybe<T> inValue)
Parameters
Returns
Remarks
This overload of the ToMaybe method prevents a Maybe<T> from being accidentally double-wrapped as a Maybe<Maybe<T>>.
ToString()
Converts the underlying value of the Maybe struct to its equivalent string representation.
public override readonly string ToString()
Returns
- System.String
A string that represents the underlying value of the Maybe struct. If the value does not exist, an empty string is returned.
Remarks
This method overrides the ToString method to provide a string representation of the Maybe struct. If the Maybe struct does not contain a value (Exists is false), this method returns an empty string.
TryGetValue(out T)
Tries to get the value of the Maybe instance.
public readonly bool TryGetValue(out T outValue)
Parameters
outValueTWhen this method returns, contains the value of the Maybe instance if it exists; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.
Returns
- System.Boolean
true if the Maybe instance has a value; otherwise, false.
Remarks
This method will return false and assign the default value of the type to the out parameter if the Maybe instance does not have a value.
Where(Func<T, Boolean>)
Filters the Maybe<T> based on a predicate.
public readonly Maybe<T> Where(Func<T, bool> inPredicate)
Parameters
inPredicateSystem.Func<T, System.Boolean>The function to test the value.
Returns
Exceptions
- System.ArgumentNullException
An System.ArgumentNullException will be thrown if the System.Func<T, TResult>
inPredicateis null (where TResult is System.Boolean). Although this might be seen as contrary to the intentions of Maybe<T>, if no System.Func<T, TResult> is provided it's considered better to fail fast than to conceal the absence of an intended action by failing silently.- System.Exception
It's possible that the System.Func<T, TResult>
inPredicate(where TResult is System.Boolean) may throw an exception when invoked.
Operators
Equality(Maybe<T>, Maybe<T>)
Determines whether two instances of Maybe<T> are equal.
public static bool operator ==(Maybe<T> inLeft, Maybe<T> inRight)
Parameters
Returns
- System.Boolean
trueif the instances are equal; otherwise,false.
Inequality(Maybe<T>, Maybe<T>)
Determines whether two instances of Maybe<T> are not equal.
public static bool operator !=(Maybe<T> inLeft, Maybe<T> inRight)
Parameters
Returns
- System.Boolean
true if the instances are not equal; false otherwise.