[Journal - Calling Open Instance Delegates in .NET Console]

Calling Open Instance Delegates in .NET Console

Sunday, March 11, 2007

Have a look at the filter user function, coded in WebEdit.NET for evaluation with the built-in code interpreter (.NET Console):

filter(array, predicate, context)
{
    var ret = new List<string>();
    foreach(s in array)
    {
        if(predicate(s, context))
        {
            ret.Add(s);
        }
    }
    ret;
}

It can be called like this, in order to grep all lines that start with line comments.

In the screen shot, you can see the auto-text list with two candidates for the second parameter. The second one, startWithEx, is just an ordinary user function, expecting a couple of string parameters, and returning a boolean value, as its use in the filter user function indicates.

More interesting is the first one. Right, the little thingy called startsWith with the red icon. What's this? It's a delegate, pointing to a function with the same signature as the startsWithEx user function.

Since recently, .NET Console code can invoke delegates directly, that is, without resorting to the Invoke() method. The result is that both delegates and user functions can be used as functors interchangeably.

Also, creating a delegate in .NET Console has become a bit easier, with the new utilities in Gregor.Core.DelegateUtil. There's a bunch of generic methods that create method and property delegates, regular, open instance, and closed static ones. There are also delegate creation function that automatically choose the delegate type, which is a type dynamically constructed from the various Callback and VoidCallback generic type definitions. Just have a look at the various routines in DelegateUtil.

Here's how startsWith has come into being:

startsWith = DelegateUtil.CreateOpenInstanceDelegate<Callback<bool, string, string>>("StartsWith")

As you probably assume, the delegate points to the StartsWith(string) method defined in the System.String class. Since it takes an extra parameter at position zero - that is, before any regular method parameters - the CreateOpenInstanceDelegate function can infer the type of the target (string) from that parameter. With that information and the method name, an open instance delegate is created, courtesy of the .NET framework 2.0.

See here for additional information on open instance and closed static delegates.