Withe the release of .NET 4.0, C# has indeed gained "scripting like" functionality with a new keyword called dynamic.
Two common uses for this keyword are to simplify complex reflection code, and simplify how we interact with COM object models.
Assume for example, that you need to use the .NET reflection API to invoke a method using traditional late binding. You could author the following code:
static void CreateUsingLateBinding(Assembly asm)
{
try
{
// Get metadata for the Minivan type.
Type miniVan = asm.GetType("CarLibrary.MiniVan");
// Create the Minivan on the fly.
object obj = Activator.CreateInstance(miniVan);
// Get info for TurboBoost.
MethodInfo mi = miniVan.GetMethod("TurboBoost");
// Invoke method ('null' for no parameters).
mi.Invoke(obj, null);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
While this method works as expected, you could simplify your code quite a bit if you use the C# 4.0 dynamic keyword:
static void InvokeMethodWithDynamicKeyword(Assembly asm)
{
try
{
// Get metadata for the Minivan type.
Type miniVan = asm.GetType("CarLibrary.MiniVan");
// Create the Minivan on the fly and call method!
dynamic obj = Activator.CreateInstance(miniVan);
obj.TurboBoost();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Notice how a bulk of the low level reflection code is out of site and out of mind. In order for this to work, a number of new concepts have been introduced into .NET 4.0, including expression trees and the DLR (dynamic language runtime). I won't get into that right now, but the short answer is we have less code to author.
Like all "shortcuts" however, the dynamic keyword has one *big* limitation. Because the underlying type and members are not know until runtime, any variable declared with the dynamic keyword will have *zero* IntelliSense! Also, the compiler will *not* check anything whatsoever (spelling, casing, etc). Therefore, the following code will compile just fine:
// Create the Minivan on the fly and call method!
dynamic obj = Activator.CreateInstance(miniVan);
obj.FOO_FOO_FOO("dkjhaskjdhsjdhks");
At runtime however, you will receive an exception from the DLR.
51d9d4e5-9a82-41b9-81a6-42c2822fd0ef|1|5.0