Functional Programming in C#, Second Edition
Out now
Functional Programming in C# teaches you to apply functional thinking to real-world problems using the C# language. The book, with its many practical examples, is written for proficient C# programmers with no prior FP experience. It will give you an awesome new perspective.
Updated for .NET 6 and C# 10.
Functional Programming in C#: Classic Programming Techniques for Modern Projects
Take advantage of the growing trend in functional programming. C# is the number-one language used by .NET developers and one of the most popular programming languages in the world. It has many built-in functional programming features, but most are complex and little understood.
Real World Functional Programming: With Examples in F# and C#
Real-World Functional Programming is a unique tutorial that explores the functional programming model through the F# and C# languages. The clearly presented ideas and examples teach readers how functional programming differs from other approaches. It explains how ideas look in F#-a functional language-as well as how they can be successfully used to solve programming problems in C#. Readers build on what they know about .NET and learn where a functional approach makes the most sense and how to apply it effectively in those cases.
// This function is not referentially transparent
// because it refers to the global DateTime.Now property
public int ElapsedDays(DateTime from)
{
DateTime now = DateTime.Now;
return (now - from).Days;
}
// Doesn't depend on the global state
public static int ElapsedDays(DateTime from, DateTime now)
{
return (now - from).Days;
}
// Dishonest signature
public static int Divide(int x, int y)
{
// If y is 0 it will throw DivideByZero exception.
// The function's signature doesn't convey enough
// information about the output of the operation.
return x / y;
}
// Honest signature
public static int Divide(int x, NonZeroInteger y)
{
// NonZeroInteger is a custom type that can
// hold any integer except zero.
return x / y.Value;
}
// or
public static int? Divide(int x, int y)
{
if (y == 0)
return null
return x / y;
}
// Assign function (x => x % 2 == 0) to a variable isEven
Func<int, bool> isEven = x => x % 2 == 0;
var list = Enumerable.Range(1, 10);
// Pass the function as an argument to Where
var evenNumbers = list.Where(isEven);
public static IEnumerable<T> Where<T>
(this IEnumerable<T> ts, Func<T, bool> predicate)
{
foreach (T t in ts)
if (predicate(t))
yield return t;
}
public static class Multpilication
{
static int counter
// An impure function as it mutates the global state
static string Counter(int val)
{
return $"{++counter} x 2 = {val}";
}
}
// A pure function
public static int MultiplyByTwo(int value)
{
return value * 2;
}