DEV Community

Siddharth
Siddharth

Posted on

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)