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:

About Me

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

Followers

Labels