### Install Strong-Named CSharpFunctionalExtensions via dotnet CLI Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Installs the strong-named version of the CSharpFunctionalExtensions NuGet package using the .NET command-line interface. ```bash dotnet add package CSharpFunctionalExtensions.StrongName ``` -------------------------------- ### Install CSharpFunctionalExtensions via dotnet CLI Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Installs the CSharpFunctionalExtensions NuGet package using the .NET command-line interface. ```bash dotnet add package CSharpFunctionalExtensions ``` -------------------------------- ### Install CSharpFunctionalExtensions via Package Manager Console Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Installs the CSharpFunctionalExtensions NuGet package using the PowerShell Package Manager Console in Visual Studio. ```powershell PM> Install-Package CSharpFunctionalExtensions ``` -------------------------------- ### Install CSharpFunctionalExtensions Analyzers NuGet Package Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md This Bash command adds the CSharpFunctionalExtensions.Analyzers NuGet package to your project, providing Roslyn analyzers for preventing misuse of Result objects and ensuring robust functional implementations. ```bash dotnet add package CSharpFunctionalExtensions.Analyzers ``` -------------------------------- ### Safely Get Dictionary Values with TryFind (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Demonstrates how to safely retrieve a value from a Dictionary using TryFind(). This method returns a Maybe, preventing KeyNotFoundException and clearly indicating the absence of a key. ```csharp Dictionary fruitInventory = new() { { "apple", 10 }, { "banana", 2 } }; Maybe appleCount = fruitInventory.TryFind("apple"); Maybe kiwiCount = fruitInventory.TryFind("kiwi"); Console.WriteLine(appleCount.ToString()); // "10" Console.WriteLine(kiwiCount.ToString()); // "No value" ``` -------------------------------- ### Compose Multiple Operations in a Single Chain with C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Shows how to chain multiple functional operations using `Result` and `Maybe` extensions. This example demonstrates retrieving a customer, ensuring a condition, promoting the customer, sending a notification, and handling the final result in a fluent manner. ```csharp return _customerRepository.GetById(id) .ToResult("Customer with such Id is not found: " + id) .Ensure(customer => customer.CanBePromoted(), "The customer has the highest status possible") .Tap(customer => customer.Promote()) .Tap(customer => _emailGateway.SendPromotionNotification(customer.PrimaryEmail, customer.Status)) .Finally(result => result.IsSuccess ? Ok() : Error(result.Error)); ``` -------------------------------- ### Explicitly Construct Maybe Type in C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Provides examples of explicitly creating `Maybe` instances using `Maybe.From()` or `Maybe.From()` with type inference, demonstrating how to wrap a value in a `Maybe` container. ```csharp Maybe apple = Maybe.From("apple"); // or Maybe apple = Maybe.From("apple"); // type inference // or var apple = Maybe.From("apple"); ``` -------------------------------- ### Safely Get First/Last Elements with TryFirst/TryLast (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Shows how to replace .FirstOrDefault() and .LastOrDefault() with TryFirst() and TryLast() to return a Maybe instead of null or a default value. This provides a safer way to access elements from collections, especially when an element might not exist. ```csharp IEnumerable fruits = new[] { "apple", "coconut", "banana" }; Maybe firstFruit = fruits.TryFirst(); Maybe probablyABanana = fruits.TryFirst(fruit => fruit.StartsWith("ba")); Maybe aPeachOrAPear = fruits.TryFirst(fruit => fruit.StartsWith("p")); Console.WriteLine(firstFruit.ToString()); // "apple" Console.WriteLine(probablyABanana.ToString()); // "banana" Console.WriteLine(aPeachOrAPear.ToString()); // "No value" Maybe lastFruit = fruits.TryLast(); Maybe anAppleOrApricot = fruits.TryLast(fruit => fruit.StartsWith("a")); Console.WriteLine(lastFruit.ToString()); // "banana" Console.WriteLine(anAppleOrApricot.ToString()); // "apple" ``` -------------------------------- ### Fluent Assertions for CSharpFunctionalExtensions Results in C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Provides an example of using `CSharpFunctionalExtensions.FluentAssertions` to write more readable and fluent test assertions for `Result` objects. This includes custom assertions like `Succeed()`, `SucceedWith(value)`, and `Fail()` for concise test validation. ```csharp var result = Result.Success(420); result.Should().Succeed(); // passes result.Should().SucceedWith(420); // passes result.Should().SucceedWith(69); // throws result.Should().Fail(); // throws ``` -------------------------------- ### Map GET Endpoint with CSharpFunctionalExtensions HttpResult Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md This C# example demonstrates how to use ToOkHttpResult() to map a Result from a service call directly to an ASP.NET HttpResult, ensuring a fluent, railway-oriented flow for API endpoints. It shows converting a Result into Results, ProblemHttpResult>. ```csharp app.MapGet("/books", (BookService service) => service.Get() //Result .ToOkHttpResult() //Results, ProblemHttpResult> ); ``` -------------------------------- ### Conditional Result Construction with SuccessIf and FailureIf in C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Demonstrates how to create successful or failed Result objects using `Result.SuccessIf` and `Result.FailureIf` methods. These methods accept boolean expressions or delegates, providing a concise alternative to traditional if/else or ternary operators. Examples include creating generic and non-generic Results based on various conditions. ```csharp bool onTropicalIsland = true; Result foundCoconut = Result.SuccessIf(onTropicalIsland, "These trees seem bare 🥥"); Result foundGrapes = Result.FailureIf(() => onTropicalIsland, "No grapes 🍇 here"); // or bool isNewShipmentDay = true; Result appleInventory = Result.SuccessIf(isNewShipmentDay, new FruitInventory("apple", 4), "No 🍎 today"); Result bananaInventory = Result.SuccessIf(() => isNewShipmentDay, new FruitInventory("banana", 2), "All out of 🍌"); // or bool afterBreakfast = true; Result orangeInventory = Result.FailureIf(afterBreakfast, new FruitInventory("orange", 10), "No 🍊 today"); Result grapefruitInventory = Result.FailureIf(() => afterBreakfast, new FruitInventory("grapefruit", 5), "No grapefruit 😢"); ``` -------------------------------- ### Represent No Value with Maybe.None in C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Shows how to use `Maybe.None` to represent the absence of a value, serving as an explicit alternative to `null` or the Null Object Pattern. Examples include conditional assignment and default values for reference and value types. ```csharp int storeInventory = ... Maybe fruit = storeInventory > 0 ? Maybe.From("apple") : Maybe.None; // or where the generic type is a reference type Maybe fruit = null; // or where the generic type is a value type Maybe fruit = default; ``` -------------------------------- ### Compare Maybe Types for Equality in C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Demonstrates how to compare `Maybe` instances for equality, including comparisons between two `Maybe` objects, a `Maybe` and a raw value, and a `Maybe` with `Maybe.None`. The comparisons correctly handle the presence or absence of inner values. ```csharp Maybe apple = "apple"; Maybe orange = "orange"; string alsoOrange = "orange"; Maybe noFruit = Maybe.None; Console.WriteLine(apple == orange); // false Console.WriteLine(apple != orange); // true Console.WriteLine(orange == alsoOrange); // true Console.WriteLine(alsoOrange == noFruit); // false ``` -------------------------------- ### Explicitly Construct Result Success and Failure (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Shows how to explicitly create Result instances in either a success or failure state. This includes creating a Result with a value, a Result with an error message, and a parameterless Result for simple success/failure indication. ```csharp record FruitInventory(string Name, int Count); Result appleInventory = Result.Success(new FruitInventory("apple", 4)); Result failedOperation = Result.Failure("Could not find inventory"); Result successInventoryUpdate = Result.Success(); ``` -------------------------------- ### Wrap Multiple Operations in a TransactionScope with C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Demonstrates how to encapsulate a series of operations within a `TransactionScope` using the functional extensions. This ensures atomicity for operations like promoting a customer and clearing appointments, with the transaction committing only if all steps succeed. ```csharp return _customerRepository.GetById(id) .ToResult("Customer with such Id is not found: " + id) .Ensure(customer => customer.CanBePromoted(), "The customer has the highest status possible") .WithTransactionScope(customer => Result.Success(customer) .Tap(customer => customer.Promote()) .Tap(customer => customer.ClearAppointments())) .Tap(customer => _emailGateway.SendPromotionNotification(customer.PrimaryEmail, customer.Status)) .Finally(result => result.IsSuccess ? Ok() : Error(result.Error)); ``` -------------------------------- ### Supply Fallback Value with Maybe.Or (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Shows how to provide a fallback Maybe or a direct value when the original Maybe has no inner value. The fallback function is only executed if the Maybe is empty, optimizing performance. ```csharp Maybe apple = "apple"; Maybe banana = "banana"; Maybe noFruit = Maybe.None; Console.WriteLine(apple.Or(banana).ToString()); // "apple" Console.WriteLine(noFruit.Or(() => banana)).ToString()); // "banana" Console.WriteLine(noFruit.Or("banana").ToString()); // "banana" Console.WriteLine(noFruit.Or(() => "banana").ToString()); // "banana" ``` -------------------------------- ### Printing Result State with ToString in C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Shows how to use the `ToString()` method on `Result` and `Result` objects to print their current state. This includes displaying the inner value for successful results or the error message for failed ones, which is useful for debugging and logging. ```csharp Result appleInventory = new FruitInventory("apple", 4); Result bananaInventory = Result.Failure("Could not find any bananas"); Result failedInventoryUpdate = "Could not update inventory"; Result successfulInventoryUpdate = Result.Success(); Console.WriteLine(appleInventory.ToString()); // "Success(FruitInventory { Name = apple, Count = 4 })" Console.WriteLine(bananaInventory.ToString()); // "Failure(Could not find any bananas)" Console.WriteLine(failedInventoryUpdate.ToString()); // "Failure(Could not update inventory)" Console.WriteLine(successfulInventoryUpdate.ToString()); // "Success" ``` -------------------------------- ### Convert Maybe to Result (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Explains how to convert a Maybe into a Result, representing the absence of a value as a failed operation with a specified error message. This is useful for integrating Maybe with error-handling patterns. ```csharp Maybe fruit = "banana"; Maybe noFruit = Maybe.None; string errorMessage = "There was no fruit to give"; Result weGotAFruit = fruit.ToResult(errorMessage); Result failedToGetAFruit = noFruit.ToResult(errorMessage); Console.WriteLine(weGotAFruit.Value); // "banana" Console.WriteLine(failedToGetAFruit.Error); // "There was no fruit to give" ``` -------------------------------- ### Conditionally Execute Operations with Maybe.Match (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Illustrates how to define two distinct operations for a Maybe: one to execute if a value is present, and another if it's absent. This allows for clear branching logic based on the Maybe's state, supporting both void-returning actions and value-mapping. ```csharp Maybe apple = "apple"; Maybe noFruit = Maybe.None; // Void returning Match apple.Match( fruit => Console.WriteLine($"It's a {fruit}"), () => Console.WriteLine("There's no fruit")); // Mapping Match string fruitMessage = noFruit.Match( fruit => $"It's a {fruit}", () => "There's no fruit")); Console.WriteLine(fruitMessage); // "There's no fruit" ``` -------------------------------- ### Filter and Extract Values from Maybe Collection (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Explains how to use `Choose` to filter a collection of `Maybe` instances, retaining only those that contain a value. It can then extract these values or map them to new ones, effectively flattening a collection of `Maybe`s into a collection of concrete values. ```csharp IEnumerable> unknownFruits = new[] { "apple", Maybe.None, "banana" }; IEnumerable knownFruits = unknownFruits.Choose(); IEnumerable fruitResponses = unknownFruits.Choose(fruit => $"Delicious {fruit}"); Console.WriteLine(string.Join(", ", knownFruits)); // "apple, banana" Console.WriteLine(string.Join(", ", fruitResponses)); // "Delicious apple, Delicious banana" ``` -------------------------------- ### Transform Maybe to Another Maybe (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Illustrates the `Bind` method, used for transforming one `Maybe` into another `Maybe`. Unlike `Map`, which transforms the inner value, `Bind` allows for a transformation that might result in a new `Maybe.None` or a `Maybe` with a different type or value. The delegate is only executed if the source `Maybe` has a value. ```csharp Maybe MakeAppleSauce(Maybe fruit) { if (fruit == "apple") // we can only make applesauce from apples 🍎 { return "applesauce"; } return Maybe.None; } Maybe apple = "apple"; Maybe banana = "banana"; Maybe noFruit = Maybe.None; Console.WriteLine(apple.Bind(MakeAppleSauce).ToString()); // "applesauce" Console.WriteLine(banana.Bind(MakeAppleSauce).ToString()); // "No value" Console.WriteLine(noFruit.Bind(MakeAppleSauce).ToString()); // "No value" ``` -------------------------------- ### Execute Action When Maybe Has No Value (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Demonstrates how to execute a void or Task returning operation only when a Maybe instance contains no value. This is useful for logging or side effects specific to the absence of a value. ```csharp void LogNoFruit(string fruit) { Console.WriteLine($"There are no {fruit}"); } Maybe apple = "apple"; Maybe banana = Maybe.None; apple.ExecuteNoValue(() => LogNoFruit("apple")); // no output to console banana.ExecuteNoValue(() => LogNoFruit("banana")); // "There are no banana" ``` -------------------------------- ### Implicit Conversion for CSharpFunctionalExtensions Results in C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Illustrates the implicit conversion feature, allowing direct assignment of a value or a string error message to a `Result` or `Result` object, respectively. This simplifies the creation of successful or failed results without explicit factory methods. ```csharp Result appleInventory = new FruitInventory("apple", 4); Result failedInventoryUpdate = "Could not update inventory"; ``` -------------------------------- ### Implicit Conversion to Maybe Type in C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Illustrates the convenience of implicit conversion when working with the `Maybe` type. This allows direct assignment of a value to a `Maybe` variable or returning a value from a method that expects a `Maybe`. ```csharp // Constructing a Maybe Maybe apple = "apple"; // implicit conversion // Or as a method return value Maybe GetFruit(string fruit) { if (string.IsNullOrWhiteSpace(fruit)) { return Maybe.None; } return fruit; // implicit conversion } ``` -------------------------------- ### Make Nulls Explicit with Maybe Type in C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Illustrates the use of the `Maybe` type to explicitly handle the absence of a value, replacing traditional null checks. This snippet shows how to retrieve a `Customer` and check if a value is present before proceeding. ```csharp Maybe customerOrNothing = _customerRepository.GetById(id); if (customerOrNothing.HasNoValue) return Error("Customer with such Id is not found: " + id); ``` -------------------------------- ### Create Result from Func or Task with Result.Of (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Explains how to use the Result.Of method to create a Result from a Func or Task. This method simplifies wrapping operations that might throw exceptions into a Result type, handling success and failure states automatically. ```csharp Result something = Result.Of(_service.CreateSomething()); Result something = await Result.Of(_service.CreateSomethingAsync()); Result something = Result.Of(() => _service.CreateSomething()); Result something = await Result.Of(() => _service.CreateSomethingAsync()); ``` -------------------------------- ### Handle Primitive Obsession with Result Type in C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Demonstrates how to use the `Result` type to encapsulate the creation of value objects like `CustomerName` and `Email`, combining their validation results to prevent primitive obsession and ensure data integrity. ```csharp Result name = CustomerName.Create(model.Name); Result email = Email.Create(model.PrimaryEmail); Result result = Result.Combine(name, email); if (result.IsFailure) return Error(result.Error); var customer = new Customer(name.Value, email.Value); ``` -------------------------------- ### Safely Access Maybe Value with Default (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Shows how to safely retrieve the inner value of a `Maybe` type, providing a fallback default value if the `Maybe` is empty. This method avoids exceptions and allows for graceful handling of missing values. ```csharp void Response(string fruit) { Console.WriteLine($"It's a {fruit}"); } Maybe apple = "apple"; Maybe unknownFruit = Maybe.None; string appleValue = apple.GetValueOrDefault("banana"); string unknownFruitValue = unknownFruit.GetValueOrDefault("banana"); Response(appleValue); // It's a apple Response(unknownFruitValue); // It's a banana ``` -------------------------------- ### Transforming Successful Results with Map in C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Explains the `Map` method, which transforms the inner value of a successful `Result` without requiring explicit checks for success or failure. The provided delegate (e.g., `CreateMessage`) is only executed if the Result is in a successful state. ```csharp string CreateMessage(FruitInventory inventory) { return $"There are {inventory.Count} {inventory.Name}(s)"; } Result appleInventory = new FruitInventory("apple", 4); Result bananaInventory = Result.Failure("Could not find any bananas"); Console.WriteLine(appleInventory.Map(CreateMessage).ToString()); // "Success(There are 4 apple(s))" Console.WriteLine(bananaInventory.Map(CreateMessage).ToString()); // "Failure(Could not find any bananas)" ``` -------------------------------- ### Convert Maybe to UnitResult (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Demonstrates converting a Maybe to a UnitResult, where the presence of an Error in the Maybe signifies a failure, or the absence of any value in the Maybe (when an error is provided) also signifies a failure. This is useful for operations that only need to indicate success or a specific error type. ```csharp Maybe error = new Error(); Maybe noFruit = Maybe.None; UnitResult weGotAnError = error.ToUnitResult(); UnitResult failedToGetAFruit = noFruit.ToUnitResult(new Error()); Console.WriteLine(weGotAnError.IsFailure); // true Console.WriteLine(failedToGetAFruit.IsFailure); // true ``` -------------------------------- ### Execute Action on Maybe Inner Value (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Demonstrates the `Execute` method, which safely performs a `void` or `Task`-returning operation on the inner value of a `Maybe` if it exists, without requiring explicit checks. The provided `Action` is only invoked when the `Maybe` contains a value. ```csharp void PrintFruit(string fruit) { Console.WriteLine($"This is a {fruit}"); } Maybe apple = "apple"; Maybe noFruit = Maybe.None; apple.Execute(PrintFruit); // "This is a apple" noFruit.Execute(PrintFruit); // no output to the console ``` -------------------------------- ### Filter Maybe Value with Predicate (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Explains how to use the `Where` method to conditionally transform a `Maybe` with a value into `Maybe.None` if a specified predicate is not met. This acts as a filter, ensuring the value only persists if it satisfies a condition. ```csharp bool IsMyFavorite(string fruit) { return fruit == "papaya"; } Maybe apple = "apple"; Maybe favoriteFruit = apple.Where(IsMyFavorite); Console.WriteLine(favoriteFruit.ToString()); // "No value" ``` -------------------------------- ### Access Maybe Value or Throw Exception (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Demonstrates how to access the inner value of a `Maybe` type. If the `Maybe` is empty, calling this method will throw an `InvalidOperationException` by default, or a custom exception if provided. This method is for procedural access when a value is expected. ```csharp Maybe apple = "apple"; Maybe noFruit = Maybe.None; Console.WriteLine(apple.GetValueOrThrow()); // "apple"; Console.WriteLine(noFruit.GetValueOrThrow()); // throws InvalidOperationException !! Console.WriteLine(noFruit.GetValueOrThrow(new CustomException())); // throws CustomException !! ``` -------------------------------- ### Check Maybe Value Presence (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Illustrates how to check if a `Maybe` instance contains a value using `HasValue` or `HasNoValue`. This is typically done before attempting to access the `Value` property directly, ensuring safe access and conditional logic based on the presence of a value. ```csharp void Response(string fruit) { Console.WriteLine($"Yum, a {fruit} 😀"); } Maybe apple = "apple"; Maybe noFruit = Maybe.None; if (apple.HasValue) { Response(apple.Value); // safe to access since we checked above } if (noFruit.HasNoValue) { Response("We're all out of fruit 😢"); } ``` -------------------------------- ### Transform Maybe Inner Value (C#) Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Demonstrates the `Map` method, which transforms the inner value of a `Maybe` if it exists, without requiring explicit checks for value presence. The provided delegate is only executed when the `Maybe` contains a value. ```csharp string CreateMessage(string fruit) { return $"The fruit is a {fruit}"; } Maybe apple = "apple"; Maybe noFruit = Maybe.None; Console.WriteLine(apple.Map(CreateMessage).Unwrap("No fruit")); // "The fruit is a apple" Console.WriteLine(noFruit.Map(CreateMessage).Unwrap("No fruit")); // "No fruit" ``` -------------------------------- ### Convert Maybe Type to String Representation in C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Shows the `ToString()` behavior of the `Maybe` type. When a value is present, `ToString()` returns the string representation of the inner value; otherwise, it returns 'No value'. ```csharp Maybe apple = "apple"; Maybe noFruit = Maybe.None; Console.WriteLine(apple.ToString()); // "apple" Console.WriteLine(noFruit.ToString()); // "No value" ``` -------------------------------- ### Transforming Failed Results with MapError in C# Source: https://github.com/vkhorikov/csharpfunctionalextensions/blob/master/README.md Demonstrates the `MapError` method, which transforms the error message of a failed `Result` or `Result` without needing to check its success/failure state. The delegate (e.g., `ErrorEnhancer`) is only executed if the Result is in a failed state. ```csharp string ErrorEnhancer(string errorMessage) { return $"Failed operation: {errorMessage}"; } Console.WriteLine(appleInventory.MapError(ErrorEnhancer).ToString()); // "Success(FruitInventory { Name = apple, Count = 4 })" Console.WriteLine(bananaInventory.MapError(ErrorEnhancer).ToString()); // "Failed operation: Could not find any bananas" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.