DEV Community

Bruce Axtens
Bruce Axtens

Posted on • Edited on

Action delegate gives Print to VBScript

Today I learned about Action delegates, for those situations where there's a void return.

I'm writing a VBScript version of my Lychen tool and wanted a "Print" command. I could have made a print "sub" and evaluated it into the VBScriptEngine with Execute or Evaluate and that would have worked fine. But I was wondering if a "function pointer" could be assigned to the Script object with the name "Print". And it turns out you can do that.

First up, it's called a delegate not a "function pointer" and these come in two flavours: Action for functions that return a void and Func for ones that return something else.

So in my Program class I have the following declaration

public static VBScriptEngine vbscriptEngine = new VBScriptEngine(WindowsScriptEngineFlags.EnableDebugging);
Enter fullscreen mode Exit fullscreen mode

and later, in an initialization routine, I have

vbscriptEngine
    .Script
    .Print = (Action<object>)Console.WriteLine;
Enter fullscreen mode Exit fullscreen mode

That bit of magic adds Print to the namespace internal to the VBScriptEngine, with said name pointing to the instance of Console.WriteLine that takes one parameter of type object.

Not much but it enables things like this (from the REPL mode (VBScript is case-insensitive)):

Lychen>print 1
1
Lychen>print "lukim yu, wantok"
lukim yu, wantok
Lychen>print CS.System.DateTime.Now.ToString("o")
2019-08-14T12:02:12.9315236+08:00
Lychen>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)