DEV Community

Siddharth
Siddharth

Posted on

5 3

Delegates - Behind The Scenes

Let's say we want to filter even numbers. In C#, we usually do it using LINQ's Where extension -

var numbers = Enumerable.Range(1, 100);
var evenNumbers = numbers.Where(n => n % 2 == 0);
Enter fullscreen mode Exit fullscreen mode

The signature of Where takes Func<int, bool> as parameter
Signature of LINQ's Where extension method

The syntactic sugar, behind the scenes, is basically doing

var evenNumbers = numbers.Where(new Func<int, bool>(n => n % 2 == 0));
Enter fullscreen mode Exit fullscreen mode

Func is a delegate which has int as input and bool as output. We can write it as -

var evenNumbers = numbers.Where(delegate(int n)
{
    return n % 2 == 0;
});
Enter fullscreen mode Exit fullscreen mode

This means we can do -

public static bool IsEven(int number)
{
    return number % 2 == 0;
}
var evenNumbers = numbers.Where(IsEven);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay