Wednesday, May 7, 2008

Dynamic lookup

A while back Charlie Calvert and Mads Torgersen wrote about dynamic lookup being part of the plans for C# 4.0. A code block specified with the "dynamic" key word will allow dynamic lookup with syntax like follows:

static void Main(string[] args) {     dynamic     {         object myDynamicObject = GetDynamicObject();         myDynamicObject.SomeMethod();         // call a method            myDynamicObject.someString = "value"; // Set a field         myDynamicObject[0] = 25;              // Access an indexer     } }

While this is a welcome feature I want it now! Of course I could resort to reflection but it gets tiresome writing all the code needed just to get a simple field or property so I made a little library that lets me write the previous example as follows:

static void Main(string[] args) {     dynamic     {         object myDynamicObject = GetDynamicObject();         myDynamicObject.Member("SomeMethod").Call();			// call a method            myDynamicObject.Member("someString").Set("value").Call();	// Set a field         myDynamicObject.Member("Item")[0].Set(25).Call();		// Access an indexer     } }

 

This also allows me to access private, protected or internal members of objects and on top of that it can compile functions for invoking the member on several instances of the same type.

I provide the code here but I'm sure there are several bugs in it so please don't use it in your applications as is. Actually please don't use it for anything like that without asking permission first...

#region Using Directives using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Globalization; using System.Reflection.Emit;