C# Delegates

Barış Tutakli
3 min readJan 29, 2022

Before learning a new subject, I often ask myself some questions to improve my learning process. So, let’s start questioning together😊

What does C# delegate mean?

Reference types let us manipulate objects by using small references instead of writing the whole object every time we need. For instance, “String”, “Arrays” and “Classes” are reference type data types. A delegate is also a reference type that holds the memory address of a method.

(A method is a block of code which might take parameters and might return a value and performs actions.)

When can I use C# delegates?

When you need to call a series of methods, you can use a single delegate to call a series of methods, or you can call two methods the same in signature using delegate. Another use of delegate is that you can pass methods as arguments to other methods.

How to Declare a delegate?

I created a method and a delegate to calculate the sum of two numbers in the code below:

Like other reference types and primitive types, we can pass delegate as a parameter. We can also set new targets using +=(-=) just like we do when we concatenate multiple strings using +=(-=). Let’s analyze delegates together in the code below!

Func Delegate and Action

Did it bother you to define delegates manually every time? Now, it’s time to learn c# Func delegate that saves us from repetitive manual works. Func is a genereic delegate.

Func<input_parameter,output_parameter>
Func<int,int> //---> output_parameter: int
Func<string,int,bool> //---> output_parameter: boolean

If a delegate does not return any value, you can use action instead of Func.

action<int> // ---> input_parameter: int

Let’s write the same code using Func:)

Predicate<T> Delegate

Let’s discover Predicate together. First i created a list of string as below:

List<string> myList = new List<string> { "Table", "Chair", "Watch", "Cup" };

I want to delete items whose length is less than 4. There are different ways to do that but i’m interesting in methods under System.Collections.Generic namespace.

myList.RemoveAll()

Press ctrl+right click on RemoveAll method, you will see a lot of methods but i need RemoveAll Method which takes Predicate<T> as a parameter and return int.

predicate

A predicate is a delegate which represents the method that defines a set of criteria and determines whether the specified object meets those criteria.

C# Predicate Delegate

So, let’s remove all items whose length is less than 4.

Do let me know your view on this 🙂 See you next time

--

--