Delegates in C#

 Introduction:

Delegates are like a pointer to a function we had in C/C++, We use delegates in c# for implementing events and callback methods.

A delegate can refer to a method with the same return type and parameters which the methods takes as of the same signature. A delegate can be declared like.

delegate <return type> <delegate-name> <parameter list>,

Public delegate int myDelegate(int x);

So a delegate can only call a function which has the same signatures as of that delegate. A delegate object can be initialized with a new key word and it can be used to call the matching method as of that paticular delegate.

Step 1

In this example, we will see we can implement delegates in c#, so lets create a new Project first in Visual studio 2017, we will name it as DelegatesExample.


 

Step 2:

We will declare a delegate with some specific name outside our Main function. So just the namespace, I will create a delegate like this.

 Step 3:

So now I will create a class with a methods to demonstrate this example, First up I will initiate two data members and then I will have 2 methods and the third function or the method will return the product of those data members.


Step 4:

Here we will create an object for DelegateTest and more importantly, we will create objects for our delegate which we declared initially.

So here we can see that obj is the object created for the DelegateTest class, P and q are the two objects we created for our delegate called myDelegate,

At lines 40 and 41, we are initiating objects for our delegates and calling the corresponding methods having the same signature as of this delegate, our delegates returns an integer and takes an integer as well as a parameter, so we can only call all those methods with that same signature.

At lines 43 and 44, we are passing parameters using our delegate objects since here the delegate acts like a pointer or a reference to a method.

At line 45, we call the multiplier method to get the product.

Here is how the entire code looks like.


Press crtl+f5 to run the Application and see the output window


  

Talha Mahmood

I have been developing Applications in Microsoft .NET technologies since 2015, and having more then 5 years of experience in .NET Technology and SQL database, also having hands in tools like C# Windows Forms, WPF, WCF, Asp.Net Web forms, Asp.Net Core, SSRS, LINQ, Entity Framework, Crystal Reports, SQL server, MySQL, MongoDB, Document DB, JQuery, JavaScript, Oracle, Web API.

Post a Comment

Previous Post Next Post