C# lambdas
Emanuel Gustafzon

Emanuel Gustafzon @emanuelgustafzon

About: Hi 👋, I am a passionate developer and I am looking forward to sharing my knowledge here on Dev. It’s great for myself and others to get a deeper understanding of software development.

Location:
Gothenburg, Sweden
Joined:
Jun 21, 2023

C# lambdas

Publish Date: Jun 27 '24
0 0

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

Comments 0 total

    Add comment