Delegates Example in C#: What are they and how do they differ?

Delegates are very important features within the .NET framework toolbox. So what are each of these features?

What and why Delegates?

A delegate when used correctly is a very powerful object that can be thought of as a pointer of sorts ( for those C and C++ developers out there :)). Specifically, pointers to methods. It allows you, the developer the ability to encapsulate a reference to another method within the delegate object.

So what does this mean? Well, lets learn by example. I find that a good example is usually a real life example. Let us say that you want a Logging tool. The catch is, you want the Logging utility to be able handle any type of logging (database, file, console etc..). In our case, we will show how easily you can use delegates to set up logging for File and Console.

Real world Examples of using Delegates

First, in the Visual Studio of your choice, create a console application. Let’s start by creating the Logger class that will hold the delegate that powers the delegate that triggers your console write and the process completion log write.

Create the logging classes

So let’s take this apart a bit. One of the main rules of delegates is that the methods that they point to must have the same exact signature as the delegate. The delegate syntax used in this case is:

public delegate void LogHandler(string(message)

This delegate is expecting any pointer methods to have 1 parameter that is of type string and no return value. This is not the only way to create a delegate, it is just an example. feel free to alter and mess around with it.

The second method is called Process(). This is used to create a new line with the typical date/time and calling method information. This can be built in an infinite number of ways. I just happened to be the easiest for an example. Also, it is worth noting that the triggering of logHandler (which is of type LogHandler delegate is what actually calls the method tied to the delegate pointer.

Now, lets move on to the Console logger class. This class will log what it needs using the delegate and then complete it’s process.

Now in this class, we define a static method called Log that has the exact signature of the delegate (the method being used can be static or a member method). You will notice that it indeed writes to the console.

 

The last part of this post is the FileLogger class. For the sake of keeping the complexity to a minimum, The FileLogger will do the same as the ConsoleLogger. We will just change the text in the Console output to distinguish the two.

Using the Delegates

As you can see, the only difference here is the string value of the console output.

Now in our console application Program.cs, lets use the following code:

The first thing you will notice is the creation of a Logger class instance. This will be used to call Process() and trigger the delegate into motion.

Delegates follow a specific process to complete motion:

  • Retrieve the method being pointed to and put it on the stack.
  • Call the method found and wait for completion.
  • Continue any code after the method is completed.

So as I said it is very important to remember that the pointer method will be trigger and complete prior to the rest of the code being executed.

After all of this, next thing you will notice is the creation of 2 new LogHandlers. This allows us to create 2 new handlers and assign a pointer to each of the methods being used. Then, the last part is using the new logger instance to call Process() which takes in a LogHandler.

Here are what the result should be upon completion of this project.

results from the console and file logging
results from the console and file logging

So in conclusion, delegates can be very powerful when you need to have callbacks (events for instance). They even can be a good alternative to interfaces when it is not necessary.

*** Note – Just as a disclaimer, this is definetly the older way of doing delegates. There are many other options not since C# 5.0+ that allow you to use things like Action,Func ect… to make it a little easier to write the code more streamlined. My next article, will most likely have that in there.

 

Happy Coding.

 

One thought on “Delegates Example in C#: What are they and how do they differ?

Leave a Reply

Your email address will not be published. Required fields are marked *