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:
- Referencing EnvDTE.dll is not required anymore – you also don’t need using EnvDTE – don’t need to reference anything!
- You declare the ‘dte’ variable to be weakly typed with the new dynamic contextual keyword
- You don’t have to cast the instance returned by Activator.CreateInstance
- You don’t get IntelliSense as you type in the last line
- 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.