Basics of delegate : C#

Introduction

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

Single delegate can be used to invoke a single method.

For example in below code, a delegate Calculate invokes a method GetSquareArea ().

Multicast Delegate

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 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s