# Fold

Creates a new `TState` value by applying the given `folder` functions to `state` and `Either<TLeft, TRight>` value according to its state.

| Parameters                                                                                                                                                                | Returns |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| <p>Func&#x3C;TState, TRight, TState> folderWhenRight</p><p>Func&#x3C;TState, TLeft, TState> folderWhenLeft</p><p>TState state</p><p>Either&#x3C;TLeft, TRight> either</p> | TState  |

## Usage

This function applies the `folder` function to the `Either<TLeft, TRight>` value and to the `state` according its state.

&#x20;**When Either IsRight**&#x20;

```csharp
int state = 20
Either<string, int> eitherValue = 22;
int result = eitherValue.Fold(
    state,
    (_state, right) => right + _state,
    (_state, left)  => _state + 10);

//result = 42
```

&#x20;**When Either IsLeft**&#x20;

```csharp
int state = 20
Either<string, int> eitherValue = "ERROR";
int result = eitherValue.Fold(
    state,
    (_state, right) => right + _state,
    (_state, left)  => _state + 10);

//result = 30
```

&#x20;**One sided approach**

You can also use the `FoldLeft` and `FoldRight` to produce the same results, but with these methods the folder is applied just to one of the possible values.

When the target type is different from `Either` current value the result always will be equals to `state`.

&#x20;**FoldRight when Either IsRight**&#x20;

```csharp
int state = 20
Either<string, int> eitherValue = 22;
int result = eitherValue.FoldRight(
    state,
    (_state, right) => right + _state);

//result = 42
```

&#x20;**FoldRight when Either IsLeft**&#x20;

```csharp
int state = 20
Either<string, int> eitherValue = "ERROR";
int result = eitherValue.FoldRight(
    state,
    (_state, right) => right + _state);

//result = 20
```

&#x20;**FoldLeft Either IsRight**&#x20;

```csharp
int state = 20
Either<string, int> eitherValue = 22;
int result = eitherValue.FoldLeft(
    state,
    (_state, left) => _state + 10);

//result = 20
```
