Delegates in C#02 Jul 2016
Lately I have been studying some topics in C# in order to improve myself. I think Delegate is one of those topics which is kinda difficult for beginners to initiate with. So, in order to make it clear how it works, I’m going to make some explanations in this post.
What are Delegates?
Delegate was introduced in C# 1. Think of it as a simply being a placeholder for functions that’ll be called at some point in time. Assume you want to declare a variable that is a reference to a specific method. In this case, the variable encapsulates some executable code and you can invoke the variable just like an actual method. In doing so, we need to create a delegate
Defining a Delegate
Delegates are created using
delegate keyword along with the function signature:
As you can see we are defining a delegate called
Sum that is compatible with any method with an
int return type with two parameters. Actually we defined a type that we can use to create variables and point those variables to methods that have the same signature and same return type.
The type defenition for a delegate describes the method that we want to call:
Now we can assign a method to the delegate variable. This assignment creates a delegate instance:
Now we can invoke the delegate instance in the same way as a method:
Advantages of Delegate
- Delegates are type safe, It means that the C# compiler checks the function signatures of a Delegate when you use them at runtime.
- Can be used to define callback functions.
- Can be dynamically switched at runtime.
Real World example
Suppose that you want to implement something like a Repeater control in your ASP.NET MVC application, As you probably know a Repeater is(was) server side databound control in ASP.NET WebForm for displaying information, It had a lot of flexability becuase you had complete control over the your markup.
As you can see we emulated the
AlternatingItemTemplate using a delegate. In this case user can pass the data and the data will be rendered inside the view. In this case the delegates act like callback.
ItemTemplate delegate in our example can be replaced with
Now we can use our helper inside any view:
If you run the application you can see the result:
You can check out the GitHub repository for this post.