using System;
using System.Reflection;
class Program {
class Duck { public string Speak() { return "quack"; } }
// *** before: ***
// a member of a type unknown at compile time was reached through
// reflection: find it by name, then Invoke it and cast the result
static string SpeakOld(object thing) {
MethodInfo method = thing.GetType().GetMethod("Speak");
return (string)method.Invoke(thing, null);
}
// *** in version 4.0: ***
// dynamic postpones the whole call to run time
static string SpeakNew(dynamic thing) {
return thing.Speak();
}
static void Main() {
Duck duck = new Duck();
Console.WriteLine(SpeakOld(duck));
Console.WriteLine(SpeakNew(duck));
dynamic value = 2;
Console.WriteLine(value + 3); // 5, addition of numbers
value = "two";
Console.WriteLine(value + "3"); // two3, joining of strings
// the price: a mistake is no longer a compiler error
try {
Console.WriteLine(SpeakNew(42));
} catch (Exception e) {
Console.WriteLine(e.GetType().Name); // RuntimeBinderException
}
}
}