A simple sample for C# 4.0 ‘dynamic’ feature

Earlier I posted some code to start Visual Studio using C# 3.0:

 using System;
using EnvDTE;

class Program
{
    static void Main(string[] args)
    {
        Type visualStudioType = Type.GetTypeFromProgID("VisualStudio.DTE.9.0");
        DTE dte = Activator.CreateInstance(visualStudioType) as DTE;
        dte.MainWindow.Visible = true;
    }
}

Now here’s the code that does the same in C# 4.0:

 using System;

class Program
{
    static void Main(string[] args)
    {
        Type visualStudioType = Type.GetTypeFromProgID("VisualStudio.DTE.10.0");
        dynamic dte = Activator.CreateInstance(visualStudioType);
        dte.MainWindow.Visible = true;
    }
}

At first, it looks the same, but:

  1. Referencing EnvDTE.dll is not required anymore – you also don’t need using EnvDTE – don’t need to reference anything!
  2. You declare the ‘dte’ variable to be weakly typed with the new dynamic contextual keyword
  3. You don’t have to cast the instance returned by Activator.CreateInstance
  4. You don’t get IntelliSense as you type in the last line
  5. The calls to dte are resolved and dispatched at runtime

It’s a trade-off, but I still view dynamic as yet another useful tool in the rich C# programmer’s toolbox to choose from.