DEV Community

Emanuel Gustafzon
Emanuel Gustafzon

Posted on

C# lambdas

In this series we have learned about delegates and event driven programming.

C# has built in delegates as we saw before with the EventHandler for events.

Now we will look at lamdas. Lambdas are highly adopted in functional programming and exist in many modern languages. It is a a way to write short hand, anonymous functions. They are concise and expressive.

Lambdas is a built in delegate in C#. As I showed in the overview, you can use delegates to write shorthand functions.

There are two types of lambdas the Funk and Action.

Both of them can take many parameters of any type.

The Funk lambda has a return type and the Action does not so if the function return void, Action is a valid choice.

The Funk lambdas last type is the return type. Funk<type, type, returnType>.

class Program {
  public static void Main (string[] args) {
    // single parameter
    Func<int, int> square = x => x * x;
    // multiple parameters
    Func<int, int, int> add = (a, b) => a + b;
    // many parameters with function body
    Func<int, int, int, bool> moreThanHundred = (a, b, c) => {
        if (a + b + c < 100) {
            return true;
        } else {
            return false;
        }
    };
    // use Action if the return type is void
    Action<int, int> print = (a, b) => Console.WriteLine(a + b);
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)