A quick look at the C# 4.0 dynamic type

VS 2010 Beta 1 includes some C# 4.0 features and though I have been reading about some of the new stuff on various blogs and forums, I only got to play with it very recently. Put simply, the dynamic keyword allows you to declare and use types that are not type-checked during compilation. They are resolved at runtime using the DLR.

Here’s a simple class that has a dynamic field, a method that has a dynamic argument, and a dynamic property:

class Dynamic
    private dynamic data;

    public void SetData(dynamic data)
        this.data = data;

    public dynamic MetaData { get; set; }

    public void Display()
        Console.WriteLine("{0} {1}, {2} {3}",
            data, data.GetType(), MetaData, MetaData.GetType());

Using the class is quite straightforward:

private void Foo()
    var d = new Dynamic();
    d.MetaData = 100; <-- Int32
    d.SetData(99); <-- Int32
    d.MetaData = 100f; <-- Single
    d.SetData("hello"); <-- String

Notice how I keep using different types at runtime for calling the same methods and properties. If you look at the IL via Reflector, you’ll see that dynamic types are internally treated as System.Object. Intellisense within VS 2010 will also give you System.Object members since that’s what they are guaranteed to have.

There are three dynamic calls in the Display method. A nested static class is generated inside the Dynamic class, and it will have one static CallSite<> field per dynamic call. In this case, there are three such fields. Whenever the dynamic calls are made, it’s these DLR call sites that come into play. An extremely simplified explanation of what happens is that the DLR internally uses reflection to figure out what type the dynamic object is at runtime. There is also caching done so that type-matching (or mapping) is not repeated unnecessarily. Of course the implementation is quite complex and you could probably spend weeks going through the code in Reflector. Note that if you make dynamic calls in a different method, there will be another static class generated – so it seems to be one inner class per method.

Consider the following simple method:

public void Test()
    var type = data.GetType();

A class will be generated similar to the following (I’ve made this easy to read – so this is not an accurate representation of the generated code):

private static class SiteContainerForTest
    public static CallSite<FUNC<CALLSITE, object, object>> callSiteGetType;

And the method Test gets compiled into:

public void Test()
    if (SiteContainerForTest.callSiteGetType == null)
        SiteContainerForTest.callSiteGetType = CallSite<Func<CallSite, object, object>>.Create(
            new CSharpInvokeMemberBinder(
                "GetType", <-- the name of the dynamic member
                new CSharpArgumentInfo[] { new CSharpArgumentInfo(CSharpArgumentInfoFlags.None, null) }

    object type = SiteContainerForTest.callSiteGetType.Target(
      this.data <-- the dynamic object

The call site’s Target will be of type Func<CallSite, object, object>, and the return type is object (because at compile time that’s what the local variable type was defined as, since we don’t know what type it would be at that time). It’s at this point that dynamic binding is done. Fortunately for us, it’s all done behind the scenes and we are protected from having to write all this code ourselves. Assuming data is an Int32 at this time, Int32‘s GetType is called (and since it doesn’t have one, Object‘s GetType is invoked).

You can also use dynamic types locally (a site container class is generated for the containing method) :

dynamic d = 1;
string s = d.ToString();

d = "dynamic data";

d = 33;

    int len = d.Length; <-- Invalid dynamic call on an Int32 object
catch (RuntimeBinderException ex)

When I try to use the non-existent Length property on an Int32 value, the runtime will throw a RuntimeBinderException. And it even gives a very useful error message : ‘int’ does not contain a definition for ‘Length’.

Overall, one of the most celebrated uses of dynamic types is supposed to be for Office interop. You no longer have to do endless casts and mid-level variables for debugging. It’s just as easy as using classic VBScript. At this point, unless you want to interop with Word or Excel, I can’t think of too many scenarios where this will come in handy. Maybe someone who’s more functionally oriented than I am can think of some common scenarios.


Tip : Flush the keyboard buffer from C#

Here’s another tip from an MSDN forum discussion. Someone wanted to know how to flush the keyboard buffer in a C# console application.

Here’s a simple hack to do this :

private static void FlushKeyboard()
    while (Console.In.Peek() != -1)

Now you can use it as follows :

char x = (char)Console.Read();
char y = (char)Console.Read();
Console.WriteLine("{0}, {1}", x, y);

Even if you enter more than a single character after the first call to Read(), the second Read() will not be affected.

An interesting week in Seattle

Last week I attended the 2009 MVP Summit held at Redmond/Seattle and I’ve got to say that I had two rather peculiar experiences whilst there. The first incident was on the way to Seattle – it snowed in Atlanta of all things to happen and this resulted in dozens of cancelled and delayed flights. My flight was scheduled for a 2:30 PM departure and after a 3 1/2 hour delay where they pushed back the boarding time every 30 minutes, we finally boarded at 6 PM. Once we got in the aircraft we waited on the tarmac for another 3 1/2 hours more before take-off as we had to wait in line behind dozens of other flights for de-icing. I am still not sure why they couldn’t have us wait outside (at the gate) and let us board after the de-icing. The air was pretty stuffy inside because the air-conditioners seemed to be at half power. And after take-off they ran out of food when it was my turn to order – so yeah, that didn’t help either. It was one of the nastiest experiences I’ve had in an airport/flight in my entire life – one that I hope will not be repeated in future.

The second incident occurred on Tuesday night (or rather Wednesday morning). I was at the Grand Hyatt (17th floor) and had gone to bed close to 1 AM as I had gone for a late dinner/chat with an old friend. Around 4:30 AM or so this really loud siren came on and an even louder announcement was repeated instructing all occupants to move to the nearest staircase and to descend to the first floor immediately. It was also announced that the elevators were shut down. I wasn’t sure if it was a fire-emergency or some temporary air-pollution – in any case, I put on my shoes, picked up my laptop and climbed down the 17 set of stairs (16 maybe if they didn’t have a 13th floor, didn’t feel like counting then). I found a few dozen equally incredulous folks downstairs wondering what the heck had just happened. We watched the fire-trucks come and the firemen go up – and all this time we were all out on the streets. A few minutes later, they said everything was alright and said we could go back up to our rooms. There was a further wait of 20 minutes or so as we waited for an engineer to come down and reset the elevator system – and I didn’t want to climb up the 17 floors, not with my laptop. The worst part of the incident was when we found out that some dim-witted inconsiderate jerk had been smoking in a non-smoking floor which was what set off the fire-alarm. So they had to evacuate that floor as well as the floors directly above and beneath it.

The nice thing about the trip was that the summit was pretty good, we had some interesting technical sessions, the food was great, and it was good to catch up with some fellow MVPs and Microsoft buddies – some of whom I’ve only met at Microsoft summits and never outside Redmond.

Follow up to writing enums to a database

In my previous blog entry, I had recommended storing enums using their string representations when writing them to a database. There’s a caveat there though – the enum names should be guaranteed to remain stable, because if you change the name of an enum member, it breaks the database. For my specific scenario I ended up using enum values with explicit short values, so if the names ever change in future the short values remain the same and thus the database remains consistent.

There are other approaches to solving this too. Reader Arnaud Weil suggests having a table for each enum and the enum id from this table is used to refer to the enums elsewhere in the database. The guys at my current project have a specialized class that emulates enums and also allows the ability to associate meta-information to each enum value (like an image or a description). A third approach would be to use custom attributes and a type descriptor that’d extract the meta-information from an enum type. The old adage is true – there are many ways to skin a cat.

When the pizza guy called me Neptune

Okay I’ve been called many things in my life, but this was a first for sure. My wife ordered pizza and I went to pick it up on my way home from work. She gave my name as Nish, and she spelled out the first letter as “N for Neptune”. I’ve heard her use “S for Saturn” too. Though they are both planets from her perspective I usually tell her that for a lot of folks, one of those is a car and the other’s an odd word they’ve never heard before. Anyway the guy on the phone wrote it down as Neptune. So when I went to pick it up I was addressed as Neptune, and though I was surprised I just thought I had misheard him. Then I saw my name on the receipt and there it was – “Neptune”. I didn’t bother correcting him of course, instead I put on my best “Lord of the sea” look and walked out with a godly swagger.

Nishant is spelt with a t at the end

I am a bit fixated on how people spell my name – for those of you who don’t know, it’s “Nishant” – 7 unrepeated letters that even a 4-year old should find it trivial to remember. Unfortunately enough, many Indian names that end in “nt” are sometimes pronounced and spelled as “nth”, so there’s a common misspelling of my name where there’s an “h” suffixed to the “ant”. Westerners never spell my name wrong, they always get it right. It’s the Indian folks who sometimes think they know what’s best and misspell my name with the trailing “h”. And sometimes it happens on my own blog. People address me using the misspelling when leaving a comment or sending me an email, and when you consider that a majority of these communications are requests for help, you’d think they’d have the basic courtesy to at least get my name correct. Oh well, at least nobody’s misspelled “Nish” so far.

A singular solicitor at Target

Smitha and I were shopping at Target this past weekend, and as is the norm these days I was pushing little Rohan around in his stroller while Smitha went through the aisles picking, unpicking and then re-picking various items that seized her interest. I was mostly bored and lost in my thoughts when I was brusquely interrupted by an unwarrantedly loud “Are you from India?” from a formally dressed middle-aged Indian gentleman. I nodded my head in affirmation as curiously enough I did happen to be from India, though for the life of me I cannot figure out what gave that away!

The next few minutes he proceeded to converse with me about how lots of Indians were in the US these days on H1 Visas, how a lot of them went on to get Green Cards, how he recently moved to Atlanta from Arkansas, how he’d be delighted to introduce his wife to me (apparently she was elsewhere in the store at that time) and a few other topics that I don’t remember right now. All I remember thinking was how to get out of this conversation, especially since I had a sneaking suspicion that this guy was trying to sell some Amway like pyramid scheme on me. Fortunately Smitha called for me at that moment and I used this opportunity to say goodbye to him, but before I could do so he handed me his business card and asked me for mine. I did not have one with me and when I said that to him, he quickly produced a piece of paper and a pen out of nowhere – honestly, I didn’t see where he took it out from, he was like a conjurer – conjuring pen and paper out of thin air. With heavy misgivings I wrote my first name and phone number on his magically produced piece of paper and gave it to him and we parted.

Needless to say, Smitha gave me a quick firing-down for giving my number to a stranger, but fortunately enough she was soon distracted by a shelf containing the oddest looking ladies’ purses I have seen in a while. Normally this would have worried me since I definitely didn’t want her carrying around one of those revoltingly unattractive purses, but at that point I was just relieved to get out of her firing line. Just then I noticed a middle aged Indian woman conversing with a young, pretty and trendily dressed Indian girl (looked like she was in her early 20s). Now I don’t want to come across as someone who eavesdrops when 2 strange women are conversing in front of me, but I couldn’t help catch a few odd words here and there. It didn’t take me too long to realize that this woman was basically dishing out the same stuff to this girl that the strange guy had earlier dished out to me, and in a minute or so I saw the hapless girl hand over her phone numbers to this lady (I distinctly remember her explicitly specifying her land, work and cell numbers). I was certain that this middle aged lady was the earlier gentleman’s spouse and at that point it became increasingly evident that they were soliciting phone numbers from Indian looking folks.

My suspicions were confirmed a little later when we left Target with Smitha’s shopping picks for the day. The middle aged couple were walking together towards the parking lot, and most markedly they did not have a single item with them (forget a bag). They had basically spent close to an hour inside Target seeking out potential Indian victims (who they hoped would be new enough to the country) and collecting their information. I fully expect to receive a phone call this week inviting me to a gathering of some sort where this gathering would most definitely be a sales talk for some crappy pyramid scheme. Obviously I would get out of it with a clever excuse but I really do feel sorry for the pretty young girl who did seem naïve enough to fall into this trap. Oh well, I suppose she will eventually learn that strange Indian looking people approaching you in the middle of a store and asking you if you are from India are to be treated with the deepest mistrust and skepticism possible. Oh, and we are going to Target this evening – Smitha wants to return a hand bag that she took half an hour to select, apparently she did not like it when she looked at it this morning and so wants a new one. Sigh!