Skip to content

Instantly share code, notes, and snippets.

@markjamesm
Last active July 31, 2021 20:39
Show Gist options
  • Save markjamesm/65740c17d9eb09b0d40435479bb30c74 to your computer and use it in GitHub Desktop.
Save markjamesm/65740c17d9eb09b0d40435479bb30c74 to your computer and use it in GitHub Desktop.
Functional C# for Beginners
// Instead of
public static int Add(int x, int y) {
return x + y;
}
// Use a lambda to add two sums
public static int Add(int x, int y) => x + y;
// Func is a delegate that can reference anything with that param signature.
// Delegates are just variables that point to functions rather than values.
// We could easily switch the Add() method for a Subtract() one here.
Func<int, int, int> Operation = Add;
// Prints 238.
Console.WriteLine(Operation(5, 233));
////////////////////////////////////////
// This func doesn't capture anything outside, so it will be treated as a method call.
// It also creates a functor, just an empty one and it is not recreated.
// A functor is a design pattern that allows for a generic type to apply a function
// inside without changing the structure of the generic type.
Func<string, string> UpperCase = str => str.ToUpper();
// Prints "HEY"
Console.WriteLine(UpperCase("Hey"));
////////////////////////////////////////
IEnumerable<int> squares =
// Use higher order functions to square items in a list
// (Select can also be thought of as Map).
Enumerable.Range(1, 5).Select(value => value * value);
// Prints 1 4 9 16 25 on newlines.
foreach (var square in squares) {
Console.WriteLine(square);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment