Page 38 - MSDN Magazine, November 2018
P. 38
C#
Create Your Own
Script Language with
Symbolic Delegates
Thomas Hansen
I love my C# compiler. My girlfriend claims I love it more than I love her, although, for obvious reasons, I’d never admit to that in public. Strong typing, generics, LINQ, garbage collection, CLI, the list of compelling traits goes on. However, every now and then I need a couple of days off from the comfortable securities with which my compiler normally provides me. For those days, I choose to code in dynamic programming languages—and the more dynamic the language, the more dangerous and fun.
OK. Enough introduction. Now let’s do what real programmers do when left alone—let’s create code:
hello world
What? You thought I said “code”? Yup, I certainly did, and that text actually is code. To understand, let’s see what you can do with this code. Take a look at Figure 1, which shows a minimalistic example of what I refer to as symbolic delegates. Create an empty console app in Visual Studio and type in the code from Figure 1.
In just 25 lines of code I’ve created my own micro programming language. To understand its advantages, realize that the “code” variable can be sent over the network; it can be fetched from a database; it can be stored in a file; and I can dynamically change the string from “hello world” to “world hello,” or to “hello hello world
world,” for that matter, and completely change the result to which it evaluates. This ability means I can dynamically combine delegates to end up with a list of function objects, sequentially evaluated, according to the code’s content. All of a sudden I’ve turned a stat- ically compiled programming language into a dynamic scripting language, simply by splitting a sentence into its words, and using the individual words as lookup keys into a dictionary. The dictionary
Figure 1 A Minimalistic Example of Symbolic Delegates
using System;
using System.Collections.Generic;
class MainClass {
public static void Main(string[] args) {
// The "programming language"
var keywords = new Dictionary<string, Action> {
// The "hello" keyword ["hello"] = () => {
Console.WriteLine("hello was invoked"); },
// The "world" keyword ["world"] = () => {
Console.Write("world was invoked"); }
};
// The "code"
string code = "hello world";
// "Tokenising" the code
var tokens = code.Split(' ');
// Evaluating the tokens foreach (var token in tokens) {
keywords[token](); }
} }
This article discusses:
• Symbolic delegates
• Creating a domain-specific language with the Lizzie
programming language
• Using Lizzie like JSON, but for code
• The need to simplify modern programming Technologies discussed:
C#, Delegates
32 msdn magazine

