Posted by Filip Ekberg on October 2 2011 4 Comments
Meanwhile I am planning and writing manuscript and code samples for my upcoming video series that will cover “Programming fundamentals using C#”, I thought it was time for a short post on some dynamic programming in C#!
Another thing worth mentioning is that I will be using Visual Studio 11 Developer Preview, if you haven’t checked it out, I posted a quick blog post about it running side by side with Visual Studio 2010!.
So, for those that are completely new and haven’t yet checked out my videos on “C# 4.0 Using the Dynamic Keyword”, here’s a quick summary:
- C# is not dynamically typed even though you can have dynamic types. It’s a statically typed dynamic type!
- ExpandoObject is the object that you use with the dynamic keyword(contextual keyword) in order to add properties and methods dynamically.
- Dynamics are evaluated at runtime
A typical dynamic setup that creates a dynamic object and adds a static amount of properties might look like this:
person.Name = "Filip";
person.Age = 24;
What is interesting about the ExpandoObject is that it implements the interface:
So what this means is that if we cast the person-object to an IDictionary we will be able to do some really cool stuff with it. The same code above but re-written to make use of the dictionary instead could look like this:
var dictionary = (IDictionary<string, object>)person;
Now you might ask why this would ever be useful? In fact I first encountered this when Rob Conery threw together a part of Massive on stage on the Norwegian Developers Conference this summer. In his case he wanted to create an extension for an IDataReader which would give you a List
So to make this as dynamic as possible, all the fields from the table was read, added with their corresponding values from the IDataReader into the dictionary, which made the whole thing very dynamic.
There are actually more ORMs(Simple.Data) out there that uses this approach, but I will get to that later on when I’ll cover DynamicObject!
This is how you add dynamic properties, but how about adding a method? It’s simple!
What you do is that you add a new key to the dictionary and the object should just be an action, like this:
When calling the Shout-method it will print out “Hellooo!!!” in the Console.
I hope you had fun reading this and that you learned something new! Stay tuned for more posts!