When Synergy .NET was released last November (with Synergy/DE 9.5), it introduced a number of new language features that are not present in traditional Synergy. One construct that is often used behind the scenes is delegates. Delegates allow you to pass methods, support callbacks, and support events in a type-safe manner.
A delegate defines a true .NET type that represents a functional declaration contract. It is similar to the C++ function pointers in that it indicates that a routine can be passed where a delegate type is declared. A delegate type declaration is similar to the prototype of a method declaration, as shown below:
delegate deleg1, void
parm1, int
enddelegate
A delegate declaration includes its name, its return type, and zero or more parameter declarations. Note that a delegate has no procedure division.
It is possible to declare fields, parameters, return types, or anything that has a type as a delegate type. The dblnet compiler enforces the rule that only items of that delegate type or a routine with a matching signature may be assigned to that field or parameter; otherwise, a TYPMISMCH error is reported. In the example below, a field is declared as a delegate type, and then method meth1, which has the same signature as deleg1, is assigned to the field.
public static method meth1, void
parm1, int
proc
end
main
record
fld1, @deleg1
proc
fld1 = meth1
In addition to assigning a field or parameter to a delegate, you can also execute a field or parameter of a delegate type. To do this, use the identifier of the field or parameter as a routine name and pass in the arguments required by the delegate. For example (using the code snippet above),
fld1(7)
would cause meth1, which was assigned to the field, to be executed with the number 7 passed as its argument value.
Using delegates enables you to take advantage of callback methods in your application design. Perhaps the most frequent use of delegates comes from their behind-the-scenes support of events, which are used throughout Windows Forms. Think of an event as a collection of delegates. When a method is added or removed from an event, the method is being added or removed from this delegate collection. When an event is raised, all delegates currently in that collection get executed. Events will be explored in more depth in a future article.
Delegates are a powerful new way of passing methods in .NET in a completely type-safe manner. We highly recommend that you try them out to see their benefits first-hand. To get you started, here’s the code in its entirety:
namespace ns1
public delegate deleg1, void
parm1, int
enddelegate
class class1
public static method meth1, void
parm1, int
proc
console.writeline(parm1)
end
endclass
endnamespace
main
record
fld1, @deleg1
proc
fld1 = ns1.class1.meth1
fld1(7)
end
For more information about Synergy/DE 9.5, see our website.