A delegate, which is also known as function pointer in C/C++, is reference type that used to hold the reference of method with specific signature, and invoke method through the delegate instance.
In .Net Delegate types are sealed and immutable type.
Types of Delegates
There are three types of delegates that can be used in C#.
- Single Delegate
- Multicast Delegate
- Generic Delegate
Single delegate can be used to invoke a single method.
For example in below code, a delegate Calculate invokes a method GetSquareArea ().
When we add or remove method to an existing delegate instance using + and – operator, it is called as multicast delegate.
For example in below code, there are four method for which take string and return number of whitespace, word, Capital Letter, lower Letter in that string. I simply add all method to delegate.
All methods will invoke in sequence as they are assigned, and we’ll get last called method return value in number.
All methods will invoke in sequence as they are assigned. Output is:
now simply add and remove one by one like:
Output is Like:
In this article I discussed the basics of delegate and how to use it.
Generic Delegate I’ll write in next post.
Your comments are valuable to me.
Happy reading 🙂