Map
Creates a new Option<T>
whose value is the result of applying the given mapping
function to Option<T>.Some
value.
Otherwise returns an Option<T>.None
.
Parameters
Returns
Func<T, TResult> mapping
Option<T> option
Option<TResult>
Usage
This function is usually used to modify an optional value by applying a given regular function. For instance, With this method is possible to apply an function that receive an int
to an Option<int>
.
This function uses the Match
method to get the encapsulated value by Option<T>
, applies the mapping
function and encapsulate the result.
When the option value IsSome
Option<int> optionValue = 4;
Option<int> result = optionValue.Map(value => value * 2);
//result.IsSome = true
//result.Some = 8
When the option value IsSome and the Map function modifies its type
Option<int> optionValue = 4;
Option<string> result = optionValue.Map(value => value.ToString());
//result.IsSome = true
//result.Some = "4"
When the option value IsSome (with named function)
int SquareAndDouble(int value)
{
return value * value * 2;
}
Option<int> optionValue = 4;
Option<int> result = optionValue.Map(SquareAndDouble);
//result.IsSome = true
//result.Some = 32
When the option value IsNone
Option<int> optionValue = Option<int>.None();
Option<int> result = optionValue.Map(value => value * 2);
//result.IsSome = false
//result.IsNone = true
Last updated
Was this helpful?