Skip to content

Commit

Permalink
README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
MrBogomips committed Dec 9, 2024
1 parent 98bcc88 commit dba4cd3
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,10 +222,32 @@ values and utilizing `Maybe<T>` methods for chaining operations.
> **Practical rule**: Use `Nullable<T>` to model class attributes and `Maybe<T>` to model return values and
> method paramethers.

## Converting `Maybe<T>` to `Result<T>`
### Recovering from `Maybe.None` with `WithDefault`

The `WithDefault` method allows recovering from a `Maybe.None` instance by providing a default value.

For example, consider the following code snippet:

```csharp
var maybeValue = Maybe.None<int>();
var value = maybeValue.WithDefault(42);
```

### Converting `Maybe<T>` to `Result<T>`

It is common to implement a pipeline of operations where an empty `Maybe<T>` instance should be interpreted as a failure,
in this case the `Maybe<T>` instance can be converted to a `Result<T>` instance by using the `ToResult` method.
in this case the `Maybe<T>` instance can be converted to a `Result<T>` instance by using the `MapToResult` method.

The `MapToResult` methods can accepts an error as a parameter and returns a `Result<T>` instance with the specified error
in case the `Maybe<T>` instance is empty.

For example, consider the following code snippet:

```csharp
var result = Maybe
.From(someFactoryMethod())
.MapToResult(new NotFoundError("Value not found"))
.Bind(ValidateValue)
.Bind(UpdateValue);

The `ToResult` method accepts an error as a parameter and returns a `Result<T>` instance with the specified error
in case the `Maybe<T>` instance is empty.
```

0 comments on commit dba4cd3

Please sign in to comment.