A simple Delegates example


In this article, we will be creating a simple application to demonstrate the use of the delegates.

What is a delegate ?

A delegate is nothing but a way of referring to a function or you can say point to a function that you have created. Might sound a bit confusing for a novice developer. Let’s discuss with an example.

Syntax of a Delegate :

Following is the syntax of the delegate

Syntax

Here, the return type of the delegate is the return type of the method that will be referenced by the delegate, parameters are the type of input parameter of the methods that can be referenced by this delegate.

So overall, this delegate can refer or point to any method that is having two input parameters of type INT32 and return type of type INT32.

So let’s use this delegate in our code. To use the delegate, we simply need to create an object of this delegate, like any other simple class, and pass the name of the method to which has the signatures similar to that of the delegate. Then, to call the delegate, we simply need to call the object and pass any argument, if the method takes any argument. See the code below :

CallDelegate

In above code, we created a delegate which can refer to a method which is having two input parameters of INT32 type and return type as INT32 (picture 1). Then we create the object and pass the name of the method which we want the delegate to refer. In final step, we call the method by calling the object of the delegate  and pass the input parameters (picture 2).

In this way we can create different type of delegates, with different return types and input parameters.

Some important points :

1. We can create a delegate which takes no input parameters and return no value.

2. Delegates act as a wrapper for the method to be called, and we can hide the actual method from the calling class.

3. They act in a type safe manner i.e. they accept method names only which match the delegate signatures and perform this check at compile time.

So this is all about the basic concept of the delegates. Happy Coding…!!!

Advertisements

About Jasminder

.Net developer and blogger by profession, keen to learn new technologies, love nature, music and cricket.
This entry was posted in C# and tagged . Bookmark the permalink.

I have a suggestion..

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