C# Delegation

C# delegation works like C/C++ function pointer (type safe). We can use delegation as the parameter of a method and pass them between methods. This helps the programmer to follow one of SOLID principles – OCP. By using delegation, we don’t have to write long and tedious if-else or switch statements. The example of using delegation is shown below:

  We create three methods which attempt to get the area from three different shapes (rectangle, circle and straight-triangle.

Shape is enum type and we use it as the parameter of the method GetShapeArea.

Do you notice that if we want to get more and more various shapes’ areas, we then have to modify GetShapeArea method to add more case. This alternatively will increase the difficulty of the code’s maintenance. Now we try to use delegation.

Do you see the difference? If we pass delegation as the parameter of the method, we then don’t have to change the method’s code. This makes the code simpler and thereby improve its productivity.

On the other hand, we can add several same format delegation and be able to remove one of them. If we write the code like this:

We will get the result of the code execution

If you don’t want to include the circle’s one. You just have to write

Anonymous delegation

Delegation can also be anonymous.

After executing the above code, you will get the console like this

There are also other types of delegation (Action, Func, Predicate)

The return type of Action is void. Action<int, char> means the parameters of Action is integer and char.

Func has the return type. Func<int,string> means the return type of the function is string and this method only has one type parameter which is integer.

Predicate means the return type of the method is always bool. Predicate<int> means the method has one integer parameter with the return type bool.