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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay