Delegates

Delegates in C# are type safe function pointers, which hold a reference to one or more methods
that have the same signature as that of a signature of a delegate.
Delegates are similar to functions pointers in C/C++.

Syntax:

delegate   

We have 2 Types of Delegates.

- Single Cast Delegates: Delegates that reference a single method.

- Multi Cast Delegates: Delegates who hold reference to more than one method.

Example 1: Single Cast Delegate.

 

using System;
namespace SampleProgram {
  //Delegate declaration
  public delegate void MyDelegate(string Text);
  class MyDelegateDemo {
    public static void Greet(string info) {
      Console.WriteLine("Hello" + info);
    }
    public static void Main() {
      //declare the delegate and pass the method Greet as reference.
      MyDelegate delGreet = new MyDelegate(Greet);
      Console.WriteLine("Greet Here !!");
      string info = Console.ReadLine();
      //call the delegate, which will invoke the Greet() method
      delGreet(info);
    }
  }
}

 

The output will be:

Greet Here!!
Good Morning!
Hello! Good Morning!

 

Multicast Delegate:

It is an extension of Single Cast Delegate. We can call more than one method using + operator in a multicast delegate.

- We have created 2 instances of SampleDelegate S1 and S2.

- S1 holds a reference to FirstMethod() and S2 holds a reference to the second method().

- S1+=S2; This statement will make S1 to point to both FirstMethod() as well as SecondMethod();

- Finally we invoke S1() which inturn will invoke both FirstMethod() and SecondMethod()

Example 2: Multi Cast Delegate.

Explanation:

- Two instances of delegates g1 and g2 created which reference to each greet method.

- g1+=g2 is equal to g1=g1+g2 which make g1 point to both methods.

- So g1() invokes both methods.

using System;
namespace SampleProgram {
  //Delegate declaration
  public delegate void MyDelegate();
  class MyDelegateDemo {
    public static void Greet1() {
      Console.WriteLine( "Hello Good Morning !");
    }
    public static void Greet2() {
      Console.WriteLine( "Hello Good Afternoon !");
    }
    public static void Main() {
      MyDelegate g1 = new MyDelegate(Greet1);
      MyDelegate g2 = new MyDelegate(Greet2);
      g1 += g2;
      g1();
    }
  }
}

 

The output will be:

Hello Good Morning!
Hello Good Afternoon!

 

 

Related Tutorials