Shiman’s Weblog

Collecting stones from the sea-shore.

C# .NET Delegates : How to use

The common blueprint for using delegates includes steps to define, create, and invoke a delegate.

1.       Define a classification of a delegate using the delegate keyword:

public delegate int DelegateClass(string info);

2.       Create an instance of a delegate using the new keyword. In the constructor, initialize the delegate with a function pointer. You can also create and initialize a delegate implicitly without the new keyword:

DelegateClass obj = new DelegateClass(MethodA);

DelegateClass obj2 = MethodA; // implicit

3.       Invoke the delegate with the call operator “()”. The call operator is convenient, but makes it harder to discern a delegate invocation from a regular function call. Alternatively, invoke the delegate with the Invoke method, which clearly distinguishes invoking a delegate from a normal function call:

obj(“1″);

obj.Invoke(“2″); // Alternative.

4.       As with any object, when the delegate is no longer needed, set the delegate to null:

obj=null;

The complete list of the example application follows:

using System;

 

namespace Examples.Delegates

{

    public delegate int DelegateClass(string info);

 

    public class Steps

    {

        public static void Main()

        {

            DelegateClass obj = new DelegateClass(MethodA);

            DelegateClass obj2 = MethodA; // implicit

            int i = obj(“1″);

            Console.WriteLine(i.ToString());

            i = obj.Invoke(“2″); // Alternative

            Console.WriteLine(i.ToString());

            obj = null;

            obj2 = null;

 

            Console.ReadKey();

        }

 

        public static int MethodA(string info)

        {

            Console.WriteLine(“Steps.MethodA”);

            return int.Parse(info);

        }

    }

}

 

August 6, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | No Comments Yet