Sebastien Lachance

Refreshing my memory : Delegates in C#

I haven’t really used delegates since I was programming with the .NET Framework 1.0. Since I have some spare time left, I decided to ‘“refresh my memory”. I have prepared a little cheat-sheet that you can use as a reminder for the delegates functionalities in the .NET Framework 3.0.

1. What is a delegate?

A delegate is a data structure that refers to one or multiples static methods and/or instance methods. You can use this when you have a dynamic list of methods to be called that you don’t know ahead of time.

2. How to create a delegate?

public class TestClass
{
private delegate void myDelegate(string name);
}

The signature of the declaration is very important! The methods that will be contained in the delegate must perfectly match the declaration. In this case, the methods that will be allowed must be void and take a single string as a parameter.

When using the delegate keyword, you are actually creating a System.MulticastDelegate.

 

3. How do I instantiate a delegate?

public void TestMethod()
{
ClassTest test = new ClassTest();

//Instantiating a delegate with an instance method
var del1 = new myDelegate(test.InstanceMethod);

//Instantiating a delegate with a static method
var del2 = new myDelegate(ClassTest.StaticMethod)
}

 

4. How do I call the method contained in the delegate?

del1.Invoke("This is a test.");

The Invoke method will actually have the same signature as your delegate signature. So you benefit of a strongly-typed way to use the delegate feature. There is also a BeginInvoke and an EndInvoke method to program asynchronously.

5. But you said that you can have more than one method in the delegate?

Actually yes. There is several ways to add more methods, but the easiest way is :

del1 += ClassTest.StaticMethod;

When calling Invoke (or BeginInvoke) each one will be executed in the order that they were added to the delegate. If an exception occurs at any point, the execution is canceled and the remaining methods will not be called. And you will get an exception of course.

5. Anything else?

Yes, a delegate is immutable. Each time you add a method entry point, a new delegate is created for you.

Comments