Introduction 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:
{codecitation class="brush: csharp; gutter: true;" width="650px"} public delegate string AmitKumar(string Amit, string Kumar); {/codecitation}
Declaration of function:
{codecitation class="brush: csharp; gutter: true;" width="650px"}
public string mcapassion(string AmitKumar, string AmitKumar_MCA04); {/codecitation}
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#:
{codecitation class="brush: csharp; gutter: true;" width="650px"}
// 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; {/codecitation} -----------------------------------------------------------------
Anonymous method example in C#:
{codecitation class="brush: csharp; gutter: true;" width="650px"} // Create a handler for a button click event McaPassion.Click += delegate(System.Object o, System.EventArgs e) { System.Windows.Forms.MessageBox.Show("Amit Kumar!"); }; {/codecitation}
OR
{codecitation class="brush: csharp; gutter: true;" width="650px"} // Create a delegate instance delegate void AmitKumar(string mcapassion);
// Instantiate the delegate using an anonymous method AmitKumar amit= delegate(string amitkumar_mca04) { /* ... */ }; {/codecitation} Thank you Amit |