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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more