Dynamic C#

So I installed VS2010 RC and am reading some books… and came across a demo of the new “dynamic” type in C# 4.0 that I thought I’d share …

The Basics

public void BasicDynamicTest()
    dynamic f = Activator.CreateInstance(Type.GetType("System.Text.StringBuilder"));
    f.Append(" World!");
    Assert.AreEqual("Hello World!", f.ToString());

The type of f is is determined at runtime.  You might be wondering why you’d want to do something like the above.  You might start thinking about evaluating expressions at runtime, a la scripting or dynamic languages like Python or Ruby.  How about something even more clever, like defining the structure of an object at runtime?


To do so, you need to create a class that inherits from the DynamicObject class and then you can do things like override the TryGetMember method so you can create your own methods on the class at runtime:

// First, make sure MyXML inherits from DynamicObject
class MyXML : DynamicObject
	private XDocument _xml = new XDocument();

	// Simple constructor
	public MyXML(string x)
		this._xml = XDocument.Parse(x);

	// Let's dynamically create our own methods
	public override bool TryGetMember(GetMemberBinder binder, out object result)
		string nodeName = binder.Name;
		result = _xml.Element("top").Element(nodeName).Value;
		return true;

public void MyXMLConstructorTest()
	dynamic xml = new MyXML(@"
	Assert.AreEqual("Alpha", xml.node1);
	Assert.AreEqual("Beta", xml.node2);


While you can basically do this with Reflection, dynamic code is much easier to deal with. You lose Intellisense on dynamic types, compile-time checking, and performance. The DLR (Dynamic Language Runtime) does the runtime interpreting for you. As the author of the book that I’m reading states, you generally wouldn’t want to use dynamic code except where you’d otherwise be using reflection; C# by nature is statically-typed so most of the time, you’re better served by writing static code.

Incidentally, the C#/.NET 4.0 book I’m reading (1 of 3) is Introducing .NET 4.0 With Visual Studio 2010 by Alex Mackey. I haven’t gotten through enough of it to have a firm opinion but I picked it up because I liked the sharp and tight focus on things that are new in 4.0 as well as the focus on MVC 2 and jQuery (there looks to be some nice interop there).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: