Functional Programming in C#: A Deep Dive into the Course’s Core Patterns
Walt Ritscher’s course is a masterclass in
functional programming (FP) for C#, and while the content is dense, I’ll break down the
key patterns you’ll encounter—along with
practical implementations—so you can start applying them immediately. Let’s focus on the
advanced patterns that set this apart from basic LINQ or reactive programming.
---
1. Pure Functions & Side-Effect Isolation
FP revolves around
pure functions: deterministic, stateless, and free of side effects. In C#, this means:
- No external state modification (e.g., no
Console.WriteLine inside a function).
- Same input → same output (no randomness or time-based changes).
Example: Refactoring an Impure Function
C#:
// Impure: Modifies external state (e.g., a file or database)
void LogUserActivity(User user) {
File.AppendAllText("activity.log", $"{user.Name} logged in at {DateTime.Now}\n");
}
// Pure: Returns a string instead of modifying state
string LogUserActivityPure(User user, string logEntry) {
return $"{user.Name} logged in at {DateTime.Now}: {logEntry}";
}
Key Takeaway: Use
dependency injection to pass in side effects (e.g., a
ILogger interface) rather than hardcoding them.
---
2. Higher-Order Functions & Function Composition
Higher-order functions (HOFs) take or return other functions. In C#, this is enabled by
delegates (
Func<>) and
expression trees.
Example: Composing Functions
C#:
// Define a pipeline of transformations
Func<int, int> pipeline = x => x
.Multiply(2) // x * 2
.Add(10) // (x*2) + 10
.Divide(3); // ((x*2)+10)/3
// Extension methods for fluency
static class IntExtensions {
public static Func<int, int> Multiply(this int _, int factor) =>
x => x * factor;
public static Func<int, int> Add(this int _, int value) =>
x => x + value;
public static Func<int, int> Divide(this int _, int divisor) =>
x => x / divisor;
}
Key Takeaway: Use
Func<> chains or
System.Interactive (Rx-style pipelines) for declarative workflows.
---
3. Monads for Error Handling (Either Monad)
The course covers
Either<Left, Right> (similar to
Result in F#) for
explicit error handling without exceptions.
Example: Implementing Either
C#:
public class Either<Left, Right> {
public bool IsLeft { get; }
public Left LeftValue { get; }
public Right RightValue { get; }
private Either(Left left) => IsLeft = true; LeftValue = left;
private Either(Right right) => IsLeft = false; RightValue = right;
public static Either<Left, Right> Left(Left left) => new(left);
public static Either<Left, Right> Right(Right right) => new(right);
public Either<Left, T> Bind<T>(Func<Right, Either<Left, T>> func) =>
IsLeft ? Left(LeftValue) : func(RightValue);
}
// Usage: Safe division
Either<string, int> Divide(int a, int b) =>
b == 0 ? Either<string, int>.Left("Division by zero") :
Either<string, int>.Right(a / b);
// Chaining operations
var result = Divide(10, 2)
.Bind(x => Divide(x, 0)); // Fails at second step
Key Takeaway: Monads
encapsulate state transitions (e.g.,
Success/
Failure). For C#, libraries like
LanguageExt provide battle-tested implementations.
---
4. Currying & Partial Application
Currying transforms
f(a, b) into
f(a)(b). Partial application fixes some arguments.
Example: Curried Function
C#:
// Curried addition
Func<int, Func<int, int>> AddCurried = a => b => a + b;
var Add5 = AddCurried(5); // Returns Func<int, int>
Console.WriteLine(Add5(3)); // 8
Key Takeaway: Useful for
configurable pipelines (e.g.,
Func<T, TResult> as middleware).
---
5. Immutable Data & Records
C# 9+
record types enforce
immutability by default.
Example: Immutable User
C#:
public record User(string Name, int Age); // Immutable by default
// "Modification" creates a new instance
var updatedUser = user with { Age = 30 }; // No side effects
Key Takeaway: Combine with
readonly struct for value types (e.g.,
Money domain objects).
---
6. Randomness in FP: Task + Either
FP handles randomness via
monadic Task (asynchronous computations).
Example: Safe Random Number
C#:
Either<string, int> GetRandomNumber() {
try {
var random = new Random();
return Either<string, int>.Right(random.Next());
} catch {
return Either<string, int>.Left("Failed to generate random number");
}
}
// Async version
async Task<Either<string, int>> GetRandomAsync() {
return await Task.Run(() => GetRandomNumber());
}
Key Takeaway: Use
Task<Either<Left, Right>> for async error handling.
---
7. LINQ as a Functional Tool
LINQ is
declarative FP in C#. The course likely covers:
- Method syntax (e.g.,
.Where() vs. SQL-like queries).
- Custom operators (e.g.,
Scan for accumulating results).
Example: Custom Scan (like F#’s Scan)
C#:
public static IEnumerable<TAccumulate> Scan<TSource, TAccumulate>(
this IEnumerable<TSource> source,
TAccumulate seed,
Func<TAccumulate, TSource, TAccumulate> func) {
var accum = seed;
foreach (var item in source) {
accum = func(accum, item);
yield return accum;
}
}
// Usage: Running total
var numbers = new[] { 1, 2, 3, 4 };
var totals = numbers.Scan(0, (acc, x) => acc + x);
//
Key Takeaway: LINQ is
lazy,
composable, and
FP-friendly.
---
8. Functional Concurrency with Task + Either
Combine
async/await with
monadic error handling:
C#:
async Task<Either<string, int>> FetchDataAsync() {
try {
var data = await _httpClient.GetAsync("api/data");
return Either<string, int>.Right(int.Parse(await data.Content.ReadAsStringAsync()));
} catch (HttpRequestException ex) {
return Either<string, int>.Left($"HTTP Error: {ex.Message}");
}
}
Key Takeaway:
No exceptions in pure code—use
Either/
Task for resilience.
---
Where to Go Next
1.
Libraries:
-
LanguageExt (FP utilities,
Either,
Option).
-
System.Interactive (Rx + FP pipelines).
2.
Books:
- *Functional Programming in C#* (Enrico Buonanno).
- *C# in Depth* (Jon Skeet) for advanced language features.
3.
Practice:
- Refactor a
legacy C# class into
immutable records +
pure functions.
- Implement a
custom Monad (e.g.,
State monad for game logic).
---
Final Thought:
FP in C# isn’t about
rejecting OOP—it’s about
composing small, testable functions with
minimal side effects. The course’s
Either and
monadic patterns are game-changers for
error handling and
async workflows.
Want a
deep dive into any specific pattern? Ask away—I’ll provide
full code examples with edge cases.