Definition and Use of .NET Framework Delegates 

The Visual J# compiler allows you to create a .NET Framework delegate, much like the delegates extension in Visual J++. The important distinction is that binding is always done at compile time.

Example

import System.Windows.Forms.*;
import System.*;

public class MyObjClass
{
    public void OnDoubleClick(System.Object o, System.EventArgs e) 
    {
        System.Console.WriteLine("test");
    }
}

public class MyClass
{
    public static void main()
    {
        MyObjClass obj = new MyObjClass();

        // Where OnDoubleClick is a method in obj.
        EventHandler handler = new EventHandler(obj.OnDoubleClick);
        handler.Invoke(obj, new EventArgs());
        // The following is also valid.
        EventHandler handler2 = new EventHandler(obj, "OnDoubleClick");
        handler2.Invoke(obj, new EventArgs());
    }
}

import System.*;

/**@delegate*/
delegate void MyDelegate(int i);

class Program
{
    public static void main(System.String [] args)
    {
        TakesADelegate(new MyDelegate(Program.DelegateFunction));
    }

    public static void TakesADelegate(MyDelegate SomeFunction)
    {
        SomeFunction.Invoke(21);
    }

    public static void DelegateFunction(int i)
    {
    Console.WriteLine("Called by delegate with number: " + i + ".");
   }
}

Output

test
test

There is support for defining .NET Framework delegates in Visual J#. (You can also define Visual J++ 6.0-style delegates, and they are of type com.ms.lang.Delegate.)

The declaration of a delegate type will consist of the following components:

  • The attribute /** @delegate */.

  • An access level.

  • The keyword delegate, or multicast delegate.

  • The return type and signature of the method the delegate type addresses.

  • The name of the delegate type, which is placed between the return type and signature of the method.

The following declares EventHandler to be a public delegate type that addresses methods taking no parameters and with a return type of void:

/** @delegate */
public delegate void EventHandler();

If a delegate type is used to address only a single method at one time, it may address a member function of any return type and signature. If, however, the delegate type addresses two or more methods simultaneously, the return type must be void.

Binding for .NET Framework delegates is always done at compile time.

Output

Called by delegate with number: 21.

See Also

Reference

Syntax for Targeting the .NET Framework
Property and Event Exposure