Modern Patterns and High-Level Features for C# - Bringing the best from Go, Rust, F#, and Swift
Corsinvest.Fx is a collection of independent NuGet packages that bring modern programming patterns and high-level features to C#. Each package is designed to be used standalone or combined with others for maximum flexibility.
Corsinvest.Fx is NOT just another FP library.
It's a pragmatic suite of modern patterns and high-level features that C# lacks natively, inspired by languages like Go, Rust, F#, and Swift.
| Principle | What It Means |
|---|---|
| Pragmatism | Solve real problems, not academic exercises |
| Safety | Catch errors at compile-time, not runtime |
| Readability | Clear, elegant code without excessive complexity |
| ModernitΓ | Best practices from modern languages |
β
Functional Patterns (when useful)
ββ ResultOf<T,E>, Option<T>, Union Types
ββ Railway-oriented programming
ββ Data transformation pipelines
β
Modern Language Features
ββ defer (Go-style resource cleanup)
ββ Inline assembly (Rust/Zig-style performance - experimental)"Solve real problems elegantly, don't chase theoretical perfection"
- Type-safe error handling without exceptions (
ResultOf<T,E>,Option<T>) - Discriminated unions with pattern matching (
[Union]attribute) - Go-style resource cleanup (
defer) - Data transformation pipelines (
Pipeextensions) - Gradual adoption in existing C# codebases
- Minimal learning curve for your team
| Scenario | Why Not | Use Instead |
|---|---|---|
| Pure FP needed | Need HKT, Free monads, lenses, etc. | LanguageExt, F# |
| Simple scripts | One-off < 100 lines, no maintenance | Plain C# |
| Team not ready | Unfamiliar with Result/Option, unwilling to learn | Traditional C# patterns |
| Batteries-included FP | Need complete FP ecosystem (HTTP, DB, etc.) | LanguageExt + ecosystem |
| Package | Description | Status |
|---|---|---|
| Corsinvest.Fx.Functional | ResultOf<T,E>, Option<T>, [Union] attribute. Railway-oriented programming, pattern matching, LINQ support. |
β Stable |
| Corsinvest.Fx.Defer | Go-style defer statements for automatic cleanup on scope exit. | β Stable |
| Package | Description | Status |
|---|---|---|
| Corsinvest.Fx.Comptime | Zig-style compile-time computation using source generators. | π§ͺ Experimental |
| Corsinvest.Fx.Unsafe | Inline assembly wrappers and unsafe operations for performance-critical code. | π§ͺ Experimental |
Install individual packages via NuGet:
# Functional programming (Result, Option, Union)
dotnet add package Corsinvest.Fx.Functional
# Go-style defer
dotnet add package Corsinvest.Fx.Defer1. Type-Safe Error Handling (Functional)
using Corsinvest.Fx.Functional;
var result = ValidateEmail(email)
.Bind(SaveToDatabase);
result.Match(
ok => Console.WriteLine("Success!"),
error => Console.WriteLine($"Error: {error}")
);2. Automatic Cleanup (Defer)
using static Corsinvest.Fx.Defer.Defer;
var file = File.Open(path, FileMode.Open);
using var _ = defer(() => file.Close());
// File closes automaticallyExperimental packages: Unsafe (inline assembly), Comptime (compile-time computation)
π See individual package READMEs for complete documentation:
- Functional - ResultOf, Option, Union types
- Defer - Resource cleanup
The examples/ folder contains practical, runnable code demonstrating all features:
- 01_OptionBasics.cs - Parsing, config, null handling
- 02_ResultOfValidation.cs - Multi-step validation
- 03_ResultOfRailway.cs - Order processing pipeline
- 04_UnionTypes.cs - Payment methods, API states, shapes
- 05_PipeWorkflow.cs - Data transformation pipelines
- 06_CombinedPatterns.cs - User registration flow (Option + ResultOf + Pipe)
- 07_OptionChaining.cs - OrElse cascading, Flatten, lazy evaluation
- 08_ResultOfRecover.cs - Recovery strategies, retry logic
- 09_DeferAsync.cs - Async resource cleanup
Run all examples:
dotnet run --project examples/Corsinvest.Fx.Examples.csprojRailway-oriented programming without exceptions:
var result = ValidateEmail(email)
.Bind(e => ValidateName(name))
.Bind(n => ValidateAge(age))
.Map(data => new User(data.Email, data.Name, data.Age))
.Bind(user => SaveToDatabase(user));
result.Match(
ok => Console.WriteLine($"Success: {ok.Value.Id}"),
error => Console.WriteLine($"Error: {error.ErrorValue}")
);Pattern matching for different states:
[Union]
public partial record PaymentMethod
{
public partial record CreditCard(string Number, string ExpiryDate);
public partial record PayPal(string Email);
public partial record BankTransfer(string Iban, string Bic);
}
decimal CalculateFee(PaymentMethod payment) => payment.Match(
creditCard => 2.5m,
payPal => 1.5m,
bankTransfer => 0.0m
);Eliminate null reference exceptions:
Option<User> FindUser(int id) =>
users.ContainsKey(id)
? Option.Some(users[id])
: Option.None<User>();
var userName = FindUser(42)
.Map(u => u.Name)
.GetValueOr("Guest");Go-style resource management:
using static Corsinvest.Fx.Defer.Defer;
void ProcessFile(string path)
{
var file = File.Open(path, FileMode.Open);
using var _ = defer(() => file.Close());
// File automatically closed on scope exit (even on exception)
ProcessData(file);
}For common issues and solutions, please refer to the Troubleshooting section in the README of the specific package you are using:
If you still need help:
- Check the examples/ folder for similar use cases.
- Search existing issues.
- Open a new issue with a minimal reproducible code sample.
# Restore dependencies
dotnet restore
# Build all projects
dotnet build
# Run all tests
dotnet test
# Run tests with coverage
pwsh tests/RunTestsAndCoverage.ps1Quality Metrics:
- β Comprehensive test suite with high coverage
- β Clean build without warnings or errors
- β Multiple real-world examples
Each package has its own detailed README:
- Functional - Result, Option, Union
- Defer - Go-Style Defer
- Unsafe - Inline Assembly (experimental)
- Comptime - Compile-Time Computation (experimental)
Contributions are welcome! Please feel free to submit issues and pull requests.
This project is licensed under the MIT License - see the LICENSE file for details.
- NuGet: Corsinvest.Fx packages
- GitHub: https://github.com/Corsinvest/dotnet-fx
- Issues: Report bugs or request features
- Project Docs: PROJECT.md - Philosophy, roadmap, decisions
Inspired by functional programming languages and modern systems languages:
- F# - Discriminated unions and Result types
- Rust - Result/Option types and pattern matching
- Go - Defer statement for resource cleanup
- Zig - Compile-time execution philosophy
- Swift - Union types and modern syntax
Made with β€οΈ by Corsinvest