delegates in C#

A delegate is a type that references a method. Once a delegate is bound to a method, it behaves like method. It can be used like other methods.


public delegate void valueEntered(string value);

Any method that matches the delegate's signature including return type, parameters etc, can be assigned to the delegate.

delegate's Overview

  • It is like a function pointer in C++.
  • It allows methods to be passed as parameters
  • It can be used as callback method.
  • In this method's signature need not to be exactly same as delegate's.
                     For Example:
                                public class type1 { }
                    public class type2 : type1 { }
                    public delegate type1 delegateEx();
                    class Program
                       {
                          static void Main(string[] args)
                           {
                             delegateEx de = new delegateEx(MethodType1);
                             delegateEx de1 = new delegateEx(MethodType2);
                           }
                          public static type1 MethodType1() { return new type1(); }
                          public static type2 MethodType2() { return new type2(); }
                        }
                   
          type1 and type2 are 2 different classes but type2 inherits type1 so It is allowed in delegates.
  • C# 2.0 introduces concept of Anonymous method which allows programmer to pass code block as parameter in method.

delegate's Example


public delegate void valueEntered(string value);
class Program
    {
        static void Main(string[] args)
        {
            delegateDemo dd = new delegateDemo();
            dd.StartDemo();
        }
    }
    public class delegateDemo
    {
        public void StartDemo()
        {
            valueEntered ve = new valueEntered(ValueEntered_Event);
            string str = Console.ReadLine();
            ve(str);
        }
        public void ValueEntered_Event(string value)
        {
            Console.Clear();
            Console.WriteLine("You Entered:" + value);
            Console.ReadLine();
        }
    }

No comments:

Post a Comment