#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)
    {
        Console.WriteLine(text);
    }

We can now invoke the method through the delegate instance.

    del1("Invoked thru delegate");
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

5 Responses to #371 – Delegate Basics

  1. Pingback: #385 – A Delegate Instance Can Refer to Both Instance and Static Methods « 2,000 Things You Should Know About C#

  2. Pingback: #549 – Anonymous Method Basics « 2,000 Things You Should Know About C#

  3. Pingback: #1,017 – Delegate Types vs. Delegate Instances | 2,000 Things You Should Know About C#

  4. Pingback: #1,018 – Delegate Invocation Syntax | 2,000 Things You Should Know About C#

  5. Pingback: #1,149 – Generic Delegate Types | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: