Two special classes when working with dynamic types:
Example: A simple example of dynamic typing:
dynamic v = "Testing"; Console.WriteLine(v.Length); // 7 v = new string[] { "One", "Two" }; Console.WriteLine(v.Length); // 2 // The following line compiles although it throws a run-time exception // of type RuntimeBinderException. It's because the compiler does not // check whether the method exists or if it has specified arguments. v.SomeMethod(8);
Example: Overload a method with an argument of type dynamic. Note that overload resolution occurs at run-time rather than at compile-time:
class Program { static void Main(string[] args) { MainClass m = new MainClass(); // Invoke MainClass.Test(string str) m.Test("Hello there!"); // "Hello there!" // Invoke MainClass.Test(dynamic) m.Test(new TestClass()); // "Hello from TestClass." } } class MainClass { // Two overloads of the Test method. public void Test(string str) { Console.WriteLine(str); } public void Test(dynamic obj) { obj.Test(); } } class TestClass { public void Test() { Console.WriteLine("Hello from TestClass."); } }
Links