Dynamic – key word, specialized form of object.
limitations – doesn’t work to lambda, doesn’t work to extension methods
when to use?
- reflection late binding methods
- COM
code examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace dynamic { class Program { static void Main(string[] args) { ChangeDynamicDataType(); Console.ReadLine(); } static void ChangeDynamicDataType() { dynamic t = "Hello"; Console.WriteLine("t is type of {0}", t.GetType()); t = false; Console.WriteLine("t is type of {0}", t.GetType()); t = 123; Console.WriteLine("t is type of {0}", t.GetType()); t = new List<int>(); Console.WriteLine("t is type of {0}", t.GetType()); t.AnyBullShitHereWillBeCompiled(); // no checks of compilator // so use try catch !!! try { t.AnyBullShitHereWillBeCompiled(); // <<< } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { Console.WriteLine(ex.Message); } } } // where can we use dynamic ? class SomeDynamicClass { // field private static dynamic myDynamicField; //property public dynamic DynamicProperty { get; set; } // return value public dynamic DynamicMethod(dynamic SomeDynamicParam) { dynamic dynamicLocalVar = "local var"; int myInt = 10; if (SomeDynamicParam is int) { return dynamicLocalVar; } else { return myInt; } } } } |
Late binding example – 2 examples – with dynamic key word and without
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
static void CreateUsingLateBinding(Assembly asm) { Type TSportsCar = asm.GetType("CarLibrary.MiniVan"); object obj = Activator.CreateInstance(TSportsCar); MethodInfo mi = TSportsCar.GetMethod("TurboBoost"); MethodInfo mi2 = TSportsCar.GetMethod("MethodWithArgs"); object[] args = {10,70} mi.Invoke(obj, null); mi2.Invloke(obj,args); } static void CreateUsingLateBindingWithDynamicKeyWord(Assembly asm) { try { Type TSportsCar = asm.GetType("CarLibrary.MiniVan"); dynamic obj = Activator.CreateInstance(TSportsCar); obj.TurboBoost(); obj.MethodWithArgs(10,70); } catch (Exception ex) { Console.WriteLine(ex.Message); } } |