John Lam 1997 — 2026

Hello, World using DynamicMethods

My Ruby bridge makes extensive use of the new DynamicMethod API in .NET 2.0. Here’s a simple example that I showed in my talk at CTTDNUG, that demonstrates how you can write “Hello, World” out to the console when someone clicks on a button on a Windows Forms app:

private void Form1_Load(object sender, EventArgs e) {
Type[] parameters = new Type[] { typeof(object), typeof(EventArgs) };
Module module = Assembly.GetExecutingAssembly().GetModules()[0];
DynamicMethod method = new DynamicMethod(String.Empty, typeof(void),
parameters, module);
ILGenerator g = method.GetILGenerator();
Type console = typeof(System.Console);
Type[] p = new Type[] { typeof(string) };
MethodInfo writeLine = console.GetMethod("WriteLine", p);
g.Emit(OpCodes.Ldstr, "Hello, World");
g.Emit(OpCodes.Call, writeLine);
g.Emit(OpCodes.Ret);
button1.Click += (EventHandler)method.CreateDelegate(typeof(EventHandler));
}