ProgrammingJavascriptCareerProductivityGadgetsASP.NETWeb Design

Working With Delegates In C# For Beginners

Written by
Published on
Modified on
Filed under
Working With Delegates In C# For Beginners

I don't normally run into delegates in my day to day coding, but at some point you will run into them and you'll want to know what they are and how they work. This has also been a popular interview question that I've received in the past, and normally one that I found difficult to answer. At the very least having a textbook definition at the ready will at least have you somewhat prepared. Good news for us, delegate are simple structures and relatively easy to use.

What are delegates?

A delegate is type that references a method in C# that match a particular signature. And by signature I mean a specific parameter list and return value. It's like a pointer to a function back in your old C++ days, but more object oriented and type safe.

Delegates can be used to pass methods as arguments to other methods. Event handlers, for example, are nothing more than methods that are invoked through delegates. You can programmatically change method calls or plug new code into existing classes. Methods must have the same return value that is defined in the delegate as well as the same parameter list.

Declare a delegate

public delegate void Del(string message);

With this delegate declaration, we can assign an instance of it to any method that returns a void and takes in a string parameter. For example:


public void method1(string str1)
{
}

public void method2(string str1)
{
}

public void method3(int int1)
{
}

public void SetDelegate()
{
    Del handler = method1;
    Del handler2 = method2;
    Del handler3 = method3; // this would return an error because the parameter list doesn't match
}

Once a delegate is instantianted, it can be invoked just like you would invoke the wrapped method. In the example above that would be:


public void SetDelegate()
{
    Del handler = method1;

    method("hello world");
    method2("hello world");
}

Delegates can be passed as parameters to other functions or assigned to properties. You can then call the delegate method at a later time (asynchronous callback). This is just one of the uses of delegates.


public void DoWork(Del handler)
{
    string strWork = "doing work";
    handler(strWork);
}

And this brings another interesting use of delegates. We can further separate logic out from our DoWork function with our passed in delegate, because DoWork doesn't require any knowledge on how handler works, and it can just perform whatever action is needed.

Multicasting


A delegate can also call more than one method when invoked. To add another method to the delegate's list of methods, called an invocation list, you can just use the + or += operators.


public class MethodClass
{
    public void Method1(string message) { }
    public void Method2(string message) { }
}


MethodClass obj = new MethodClass();
Del d1 = obj.Method1;
Del d2 = obj.Method2;
Del d3 = DelegateMethod;

//Both types of assignment are valid.
Del allMethodsDelegate = d1 + d2;
allMethodsDelegate += d3;

At this point when allMethodsDelegate is invoked, it will actually call all 3 methods in its invocation list in the order that they were added.

In that same logic, you can also remove methods from the invocation list using the - operator.


allMethodsDelegate -= d1;

This would remove the d1 method from the invocation list associated with allMethodsDelegate;

This was just a quick introduction into the world of delegates and will at least give you the textbook definition that may come in handy at some point during an interview. There's plenty more in the world of delegates though, including using them with anonymous functions which I will talk about soon. Happy coding!

Walter Guevara is a software engineer, startup founder and currently teaches programming for a coding bootcamp. He is currently building things that don't yet exist.

Comments

No messages posted yet

Developer Poll

Q:

Stay up to date

Sign up for my FREE newsletter. Get informed of the latest happenings in the programming world.

Add a comment

Keep me up to date on the latest programming news
Add Comment

Stay up to date

Get informed of the latest happenings in the programming world.

No thanks