Functional Programming using C# 4.0 – Functional Composition

C# 4.0 treats functions as regular objects which enables programmers to use functions as arguments of other functions. Functions those take other functions as arguments are technically called as higher order functions. Functional composition is one such example of higher order functions. Functional composition is a functional programming concept in which two or more functions can be combined to compose a higher order function.


Functional composition is a feature supported as part of functional programming features in C# 4.0. Suppose, say we have two functions represented by generic types: Func which converts type x to type y and Func which converts type y to type z. Then a new function represented by the generic Func can be composed out of two generics to convert type x directly to type z. This is called functional composition.

Code Snippet

Code snippet for functional composition (for example described above):

static Func ComposeFuncs(Func f1, Func f2)
return (x) => f2(f1(x));


The generic function shown in the code snippet above can be used in various scenarios. Following is an example:

Func f = 2 * x + 3;
Func g = x * x;
Func gf = ComposeFuncs (f, g); //equivalent to
(2 * x + 3) * (2 * x + 3)
double y = gf(3); // result would be 81

Here is an example of reverse; i.e.

Func fg = ComposeFuncs (g, f); //equivalent to
2 * x * x + 3
double y2 = fg(3); // result would be 21

Two transforms g(f(x) )and f(g(x)) are different!


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: