Dynamic member lookup C# with Example



Dynamic member lookup C# with Example

A new pseudo-type dynamic is introduced into the C# type system. It is treated as System.Object, but in addition, 
any member access (method call, field, property, or indexer access, or a delegate invocation) or application of an 
operator on a value of such type is permitted without any type checking, and its resolution is postponed until run- 
time. This is known as duck typing or late 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. 
 

0 Comment's

Comment Form

Submit Comment