Page 173 - CSharp/C#
P. 173

binding. For example:


         // Returns the value of Length property or field of any object
         int GetLength(dynamic obj)
         {
             return obj.Length;
         }

         GetLength("Hello, world");        // a string has a Length property,
         GetLength(new int[] { 1, 2, 3 }); // and so does an array,
         GetLength(42);                    // but not an integer - an exception will be thrown
                                           // in GetLength method at run-time


        In this case, dynamic type is used to avoid more verbose Reflection. It still uses Reflection under
        the hood, but it's usually faster thanks to caching.

        This feature is primarily targeted at interoperability with dynamic languages.


         // Initialize the engine and execute a file
         var runtime = ScriptRuntime.CreateFromConfiguration();
         dynamic globals = runtime.Globals;
         runtime.ExecuteFile("Calc.rb");

         // Use Calc type from Ruby
         dynamic calc = globals.Calc.@new();
         calc.valueA = 1337;
         calc.valueB = 666;
         dynamic answer = calc.Calculate();


        Dynamic type has applications even in mostly statically typed code, for example it makes double
        dispatch posible without implementing Visitor pattern.

        Read C# 4.0 Features online: https://riptutorial.com/csharp/topic/3093/csharp-4-0-features








































        https://riptutorial.com/                                                                             119
   168   169   170   171   172   173   174   175   176   177   178