How to create com.ms.lang.Delegate in J#
Creating com.ms.lang.Delegate in J#
Single-cast Delegate
Single-cast Delegate derived from com.ms.lang.Delegate calls only one function. This delegate type represents objects that cannot be chained together in an invocation list.
The Syntax for the single-cast delegate is shown below:
delegate int TestDelegate (int a, int b);
As you can see, the “delegate” keyword is used to declare a Single cast delegate derived from com.ms.lang.Delegate. When compiler encounters the above statement, it will create a new class called TestDelegate which as said, would have been derived from com.ms.lang.Delegate.
Since, this type of Delegate cannot be combined, hence combining it with any other delegate will throw an exception saying:
com.ms.lang.MulticastNotSupportedException: class check does not support multicasting
For example, following program would throw an exception as mentioned as above:
import com.ms.lang.*;
delegate void check(int a, int b);
public class test
{
public void greater(int a, int b)
{
if (a > b)
System.out.println("Greater");
else
System.out.println("Small");
}
public void lower( int a, int b)
{
return;
}
public static void main(String args[])
{
test t = new test();
check ch = new check(t, "greater");
check ch1 = new check(t, "lower");
Delegate.combine(ch, ch1);
}
}
Multicast Delegates
Multicast Delegates derived from com.ms.lang.Delegates can be a part of the link list and always points to the head of the link list. The Syntax for the single-cast delegate is shown below:
multicast delegate void TestDelegate (int a, int b);
As you can see “multicast” keyword along with “delegate” keyword is used while declaring a multicast delegate in J#. The return type of this muticast delegate cannot be anything else than void else VJ# compiler: vjc compiler would throw an error.
It needs to be noted that only delegates which are of the same type (i.e. which belongs to the same class) can be combined. You can also not combine a mutlicast and a single-cast delegate. For example, the following program would an exception saying:
java.lang.IllegalArgumentException: cannot combine Delegates of different types
import com.ms.lang.*;
multicast delegate void multi_check(int a, int b);
delegate void single_check(int a, int b);
public class test
{
public void greater(int a, int b)
{
if (a > b)
System.out.println("Greater");
else
System.out.println("Small");
}
public void lower( int a, int b)
{
return;
}
public static void main(String args[])
{
test t = new test();
multi_check ch = new multi_check(t, "greater");
single_check ch1 = new single_check(t, "lower");
Delegate.combine(ch, ch1);
ch.invoke(21, 20);
}
}
Comments
- Anonymous
March 17, 2006
While I was trying to write a blog around the topic of Delegates in J#, I found that a few blogs have...