13.9. Calling Generic Delegates

Generic delegates cannot be defined within J#. However, in sticking with our "consumer-only" theme, they are allowed to be constructed and used with J#. To illustrate this point, you must first define a delegate in one of the generic-producer languages (C# for this example). Its declaration appears as follows:

[C# code]
public delegate void SampleDelegate<T, U>(T val1, U val2);

With this delegate defined, you can then import and use it freely throughout your J# solutions. The following example represents an example of this delegate being employed with J#:

[J# code]
public class TestGenericDelegates {
    public TestGenericDelegates() { }

    public void ProcessItems(SampleDelegate<String, double> aDelegate) {
        aDelegate.Invoke("Param1", 929.00);
    }

    public void Processor(String val1, double val2) {
        System.out.println(val1);
        System.out.println(val2);
    }

    public void CallMethodWithDelegate() {
        SampleDelegate<String, double> myDelegate =
                                 new SampleDelegate<String, double>(Processor);
        ProcessItems(myDelegate);
    }
}

You'll notice the ProcessItems() method here references the SampleDelegate<T, U> as the type for its parameter. The Processor() method is then declared with a signature that matches that of the declared delegate, allowing it to be successfully instantiated and passed as a parameter in the CallMethodWithDelegate() method.

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.