A delegate is a type which stores reference to a method. It is much similar to function pointers in C and C++ but delegates are type-safe and secure.
Once a reference is stored in delegate it behaves very similar to the referenced method. Parameters can be passed and values can be returned in a similar fashion.
Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate.
There are mainly three ways of assigning method references to delegates :
1. Named static methods
2. Named Instance methods
3. Anonymous methods : Supported from CSharp 2.0 onwards.
Consider the following working program:
1: using System;
2: using System.Collections.Generic;
3: using System.Text;
4:
5: namespace Vikas.Goyal.Delegates
6: {
7: class Program
8: {
9: delegate void Del(string name);
10: static void Main(string[] args)
11: {
12: /* Named Static Method */
13: Del handler;
14: handler = SampleClass.StaticMethod;
15: handler("Vikas");
16:
17: /* Named Instance Method */
18: SampleClass sc = new SampleClass();
19: handler = sc.InstanceMethod;
20: handler("Vikas");
21:
22: /* Anonymous Method supported from C# 2.0 */
23: handler = delegate(string name)
24: {
25: System.Console.WriteLine("Hi " + name + " : A message from the anonymous method.");
26: };
27: handler("Vikas");
28: }
29: }
30:
31: class SampleClass
32: {
33: public void InstanceMethod(string name)
34: {
35: System.Console.WriteLine("Hi "+name+" : A message from the instance method.");
36: }
37:
38: static public void StaticMethod(string name)
39: {
40: System.Console.WriteLine("Hi " + name + " : A message from the static method.");
41: }
42: }
43:
44: }
Line 9 shows declaration of the delegate.
Line 12 to 15 shows implementation & execution using named static method.
Line 17 to 20 shows named instance method
Line 22 to 27 shows anonymous method implementation.
OUTPUT :
Hi Vikas : A message from the static method.
Hi Vikas : A message from the instance method.
Hi Vikas : A message from the anonymous method.
Delegates are extensively used to implement callback methods while designing asynchronous systems.
Anonymous delegates helps in avoiding creation of a separate method.
No comments:
Post a Comment