delegate creation

A delegate is defined with delegate keyword.

A delegate is a type for method.

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;

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:


33

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.

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.