delegate

In this chapter you will learn:

  1. Get to know delegate
  2. How to create a delegate
  3. instance delegate method reference

Get to know delegate

A delegate is a type for method. The method referenced by delegate can be called through the delegate. A delegate in C# is similar to a function pointer in C/C++. The same delegate can call different methods.

A delegate is declared using the keyword delegate. The general form of a delegate declaration:

delegate ret-type name(parameter-list);
  • ret-type is return type.
  • The parameters required by the methods are specified in the parameter-list.

A delegate can call only methods whose return type and parameter list match those specified by the delegate's declaration.

All delegates are classes that are implicitly derived from System.Delegate.

Create delegate

The following code defines a delegate.

delegate void Printer(int i);

Here the Printer is the name of the delegate. It is like the name of the class or a struct. Later we can use it as a type.

using System;/*from  jav a  2s  .c  o m*/

delegate void Printer(int i);
class Test
{
    static void consolePrinter(int i)
    {
        Console.WriteLine(i);
    }
    static void Main()
    {

        Printer p = consolePrinter;
        p(33);

    }
}

The output:

In the code above we define a variable p whose type is Printer. delegate defines a way we should follow to create methods. Then later we can use the delegate type to reference the methods with the same form. Printer delegate requires that the type of method should take single int type as input and return void.

instance delegate method reference

To add instance method from a type(class) we have to reference the instance type name.

using System;//from   jav  a  2  s  . c  om

delegate void Printer(int i);
class MyClass
{

    public void consolePrinter(int i)
    {
        Console.WriteLine(i);
    }

}

class Test
{
    static void Main()
    {
        MyClass cls = new MyClass();

        Printer p = cls.consolePrinter;
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use multicast delegate
  2. Example to create multicast delegate
  3. Subtract delegate
  4. Use new operator to create delegate
Home » C# Tutorial » delegate, lambda, event
delegate
Multicast delegate
delegate variables
delegate parameters
Generic delegate
delegate return
Func and Action
delegate new
chained delegate
Anonymous delegate
delegate array
Return a delegate
delegate as parameter
Event
event multicast
static event
EventHandler
Event pattern
lambda
lambda syntax
Func, Action and lambda
lambda with outer function
lambda iteration variables