If you’re comfortable with javascript, python, ruby, or any other dynamically typed programming language for that matter, the new dynamic type in C# 4.0 shouldn’t be too much trouble to understand. In fact, I think I can sum it all up in three lines of code:
namespace VS_2010_Sandbox
{
class Program
{
static void Main(string[] args)
{
GetFirstName(new { FirstName = "Evan"}); //1
}
public static void GetFirstName(dynamic m) //2
{
Console.WriteLine(m.FirstName); //3
Console.ReadLine();
}
}
}
Pretty simple. Before C# 4.0, the compiler would throw an error if I wrote “m.FirstName”–that is, unless, of course, m’s class contained a public property named FirstName.
In the old days, then, (back when I was a kid), your GetFirstName method would use reflection to retrieve the value of FirstName, and would thus look something like the following. Ah, those were the days:
namespace VS_2010_Sandbox
{
class Program
{
static void Main(string[] args)
{
GetFirstName(new { FirstName = "Evan"});
}
public static void GetFirstName<T>(T m)
{
string firstName = typeof(T).GetProperty("FirstName").GetValue(m, null) as string;
Console.WriteLine(firstName);
Console.ReadLine();
}
}
}
With our new dynamic type, if we try to call something that doesn’t exist in the class (say, m.LastName), the code will compile, but we’ll get a runtime error that’s equivalent to the error that we would’ve gotten (back in the days) at compile time. Seems a wee bit hairy, I know, but I’m willing to run with it (pun intended). Mads Torgersen talks a little bit about this (and much more) in the Channel 9 video, Inside C# 4.0.
This Seems Stupid
I know what you’re thinking. On first take, the dynamic type doesn’t seem super-handy. But there are a few instances where it might be really useful. And I can imagine that, sooner or later, some asshole (not me) will use the dynamic type to conjure up some truly mindblowing code.
Use 1: Working with an Object Spawned from the Annals of a Dynamic Language
Check out the example on Scott Hanselman’s blog. Or, here’s another example:
ScriptRuntime py = Python.CreateRuntime();
dynamic isSpam = py.UseFile("spam.py");
//get spam score
double spamScore = isSpam.Rate("Need Viagra? Try public wrestling.");
Use 2: Building Dynamic Objects
Here’s a nice Channel 9 video that explains how you can get rid of (or maybe most of) your XmlDocument(“…”).GetElement(“..”) calls with dynamics:
//instead of writing this:
var doc = new XmlDocument("/path/to/file.xml");
var baz = doc.GetElement("foo").GetElement("qux");
//you can write:
dynamic doc = new XmlDocument("/path/to/file.xml");
var baz = doc.foo.qux;
Use 3: Invoking a Method on a Set of Objects That Do Not Share a Suitable Base Class
Brian Mains’ post details one such example. Though this usage of dynamics likely implies a lurking, pungent code smell, it at least relieves the need to create lengthy if..else statements or, ghast, switch cases to access the “shared” method or property. For example, Brian went from using:
public string DataSourceID
{
get
{
//DataSourceId is not inherited from a shared base class,
//so Brian had to do this:
if (_control is GridView)
return ((GridView)_control).DataSourceID;
else if (_control is DetailsView)
return ((DetailsView)_control).DataSourceID;
}
}
To using:
dynamic _control;
public string DataSourceID
{
get { return _control.DataSourceID; }
set { _control.DataSourceID = value; }
}
Use 4: Uh, ExpandoObject
Within the first four minutes of playing with the
dynamic m = new dynamic();
m.GodDamnIt = "Why don't you work?";
Don’t feel humiliated when the compiler burps, cries, farts, etc. All faith isn’t lost. You actually can do something like this; you just have to instantiate the ExpandoObject class. Below is a nice demo from David Morton’s blog. I’m sure something useful could come of this:
dynamic x = new ExpandoObject();
x.SomeText = "This is some text";
x.Value = 30;
x.Run = new Action(() => Console.WriteLine("Running a recently added method!"));
Console.WriteLine(x.SomeText);
Console.WriteLine(x.Value);
x.Run();
There are plenty of other ways to use the dynamic type, many more of which are surely being conjured up right now, as I speak, at this very moment, and this one, in front of your face, or behind it, so keep your eye out for the innovations (creepily, I whisper to you: “they’re coming”), and do let me know if anything mindblowing passes your way, or if you have anything that you’d like to add.
Read More
You can leave a response, or trackback from your own site.
4 Responses to “Dynamic Type in C# 4.0: Explained in Three Lines of Code”
Leave a Reply


[...] by Evan in 2010, 4.0, C#, Visual Studio So, yesterday, I posted what I believed to be a fairly civil and balanced post about the benefits and the possible dangers of using the new dynamic type in C# 4.0. Ultimately, [...]
Dynamic Type in C# 4.0: Explained in Three Lines of Code…
Thank you for submitting this cool story – Trackback from DotNetShoutout…
[...] Dynamic Type in C# 4.0: Explained in Three Lines of Code & Dynamic Type in C# 4.0: The Cool New Thing To Crap On – Evan Nagle sets out exploring the new C#4 dynamic support with a simple 3 line example showing how it can be used, comparing it to the older reflection based way of achieving similar, and moves on to look at some of the more advance uses in loading dynamic scripts and calling their functionality, duck typing, and the ExpandoObject. His follow on post answers a number of the criticisms of dynamic in C# received in response to the first article. [...]
That’s cool stuff! I was expecting this since I started using Reflection.