#371 – Delegate Basics

In C#, a delegate allows you to create an object that refers to a method.  This object can be thought of as a sort of pointer to the method.

You use the delegate keyword to define a type that can be used to create objects that point to methods having a particular signature.

private delegate void StringHandlerDelegate(string s);

In this example, we define a new delegate type that knows how to point to methods that take a single parameter, of type string, and whose return type is void.

The term delegate refers to this new delegate type.  We can now create an instance of the delegate that points to a specific method.

    static void Main()
        StringHandlerDelegate del1 = Method1;

    static void Method1(string text)

We can now invoke the method through the delegate instance.

    del1("Invoked thru delegate");