Learning Delegates In C#

Introduction

There is this thing in C# called a delegate, which is going to be crucial to build interactions between our objects.

What is a delegate in C#?

A delegate is a pointer to a method. What does that mean? Just like you can pass a variable by reference, you can pass a reference to a method. Let me give you an example.

Let's say we have a class with two methods that have the same signature (same return type and same parameter configuration).

public class MyObject
{
    public int Add(int param1, int param2)
    {
        return param1 + param2;
    }
    public int Multiply(int param1, int param2)
    {
        return param1 * param2;
    }
}

We can point to either of the methods in our class by using a delegate declared as follows.

public delegate int MyMethodDelegate(int param1, int param2);

Now, if we have another class and want to execute either of the methods in MyObject, we can do it through the delegate as in the "Do()" method in the class below As a matter of fact, we can pass any method with the same signature (not JUST the methods in MyObject).  Check out the MySecondObject.Subtract() method.

public class MySecondObject
{
    MyObject obj;
    int a, b;
    public MySecondObject()
    {
        a = 4;
        b = 5;
        obj = new MyObject();
    }
    public int Do(string pMethod)
    {
        MyMethodDelegate del = null;
        switch (pMethod)
        {
            case "Add":
                del = new MyMethodDelegate(obj.Add);
                break;
            case "Multiply":
                del = new MyMethodDelegate(obj.Multiply);
                break;
            case "Subtract":
                del = new MyMethodDelegate(this.Subtract);
                break;
        }
        if (null == del)
            throw new Exception("Not a valid call");

        return del(a, b);
    }
    public int Subtract(int param1, int param2)
    {
        return param1 - param2;
    }
}

Hopefully, this gives you a better idea of what delegates are and how they are implemented.


Similar Articles