Understanding Delegates in C#: The Complete Beginner’s Guide
dev.to·16h·
Discuss: DEV
Flag this post

Delegates in C

In C#, a delegate is a type-safe object that holds a reference to a method.

It allows you to pass methods as parameters, store them in variables, and call them dynamically, enabling flexible and reusable code.


🧩 Example Without Delegates

Let’s say we want to filter a list of integers based on different conditions.

In many programs, we perform similar operations that differ only by a specific rule — for example, filtering numbers based on various criteria.

internal class Program
{
static bool IsPositive(int item)
{
return item > 0;
}

static void FilterPositive(List<int> items)
{
foreach (int item in items)
{
if (IsPositive(item))
{
Console.WriteLine(item);
}
}
}

static void Main(string[] args)
{
List<int> list = new List<int>() {...

Similar Posts

Loading similar posts...