Functional Features of C#
C# is a multi-paradigm language. It allows writing code in a functional style.
Records
Records allow easily to define immutable structures, which is something very important in pure functional languages.
Functions within functions
There are two ways to create a function within another function:
-
lambdas
-
function definitions (since C# 7)
Both these ways result in separate classes being created by the compiler.
Tuples
Tuples are useful since in functional programs there may be lots of small functions returning its own data. It would clutter the codebase to define types with return values of all these functions.
Since C# 7, tuples are much more pleasant to use and more performant. They are treated as value types, and they are mutable.
Tuple’s items can be named:
Example:
Switch Statement
Since the C# 8, switch
works similarly to Rust’s switch
thanks to pattern
matching.
Delegates
Custom-defined delegates are rarely used nowadays thanks to the generic Func
and Action
. These can be even used when “classic” delegates are expected.
However, sometimes defining a custom delegate is actually useful because it
allows us to name it. Clock
looks better than Func<DateTime>
when we’re looking
at function signatures.