using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleDynamicVariables { class Program { static void Main(string[] args) { DemoDeclaring(); DemoAccessingMembers(); DemoRunTimeExceptions(); Console.ReadLine(); } private static void DemoDeclaring() { Console.WriteLine("Declaring dynamic variables"); Console.WriteLine("==========================="); // Declare a dynamic variable and assign it a string initially. dynamic t = "Hello world!"; Console.WriteLine("t is of type: {0}", t.GetType()); // Now assign an int to the dynamic variable. t = 180; Console.WriteLine("t is of type: {0}", t.GetType()); // Now assign a List to the dynamic variable. t = new List(); Console.WriteLine("t is of type: {0}", t.GetType()); } private static void DemoAccessingMembers() { Console.WriteLine("\nAccessing members on dynamic variables"); Console.WriteLine("======================================"); // Declare a dynamic variable and assign it a string initially. dynamic t = "Hello world!"; t = t.ToUpper(); Console.WriteLine("t is {0}", t); // Now assign an int to the dynamic variable. t = 180; t = t * 2; Console.WriteLine("t is {0}", t); // Now assign a List to the dynamic variable. t = new List(); t.Add("Huey"); t.Add("Lewey"); t.Add("Dewey"); Console.WriteLine("t has {0} items", t.Count); } private static void DemoRunTimeExceptions() { Console.WriteLine("\nRun time exceptions can occur..."); Console.WriteLine("======================================"); // Declare a dynamic variable and assign it a string initially. dynamic t = "Hello world!"; // It's a string :-) t = t.ToUpper(); // This will work fine. t.Add("Huey"); // This will cause an exception. Console.WriteLine("t is {0}", t); } } }