Wednesday, September 30, 2009

What is Delegate in .net(Delegate,Named method,Anonymous method)

A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value.

In simple words,delegates are similar to pointer to a function in C++ but delegate are type safe. Delegates can be defined as methods that are used to call other method. The things which we need to consider is that the signature of the calling methods and delegates should match.

Example:

In C#:

Declaration of Delegate:

public delegate string AmitKumar(string Amit, string Kumar);

Declaration of function:

public string mcapassion(string AmitKumar, string AmitKumar_MCA04);

Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own delegated method.

A delegate can be associated with a named method and anonymous methods. When you instantiate a delegate using a named method, the method is passed as a parameter, and in the case of anonymous methods code block passed as a delegate parameter.

Named method example in C#:

// Declare a delegate:
delegate void AmitKumar(string mcapassion);

// Define a named method:
void McaPassion(string amitkumar_mca04) { /* ... */ }

// Instantiate the delegate using the method as a parameter:
AmitKumar amit = obj.McaPassion;
-----------------------------------------------------------------

Anonymous method example in C#:

// Create a handler for a button click event
McaPassion.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Amit Kumar!"); };

OR

// Create a delegate instance
delegate void AmitKumar(string mcapassion);

// Instantiate the delegate using an anonymous method
AmitKumar amit= delegate(string amitkumar_mca04) { /* ... */ };
Share:

0 comments:

Sitecore® Technology MVP 2019

Featured Post

Sitecore Error Troubleshooting: Sitecore Solr Connectivity Issue:: Part-1

Sitecore Error Troubleshooting: Sitecore Solr Connectivity Issue:: Part-1 How to verify Sitecore 9.1 (IaaS and Azure PaaS) + Solr (IaaS) C...

Total Pageviews

State Counder

Popular

About Me

My photo
Based in Bangalore, INDIA, Amit is a Sitecore MVP and MCC. He has an MCA from the U.P.T.U., INDIA and holds certifications including Sitecore and SharePoint 2007/2010. He is an contributor to Sitecore/MSDN communities and http://amitkumarmca04.blogspot.com/. Amit have experience in Sitecore, ASP.Net with C#, MVC, SharePoint, Classic ASP, VB,Macros,HTML,JavaScript,JSON,BootStrap and AngularJS.

Followers

Follow me on Twitter

Labels