C# 4.0 dynamic Objects
Revisiting the C# 4.0 article (see my earlier post), new features introduced in C# 4.o can be grouped under the following
Dynamic binding
Named and optional arguments
Variance
Today I’ll discuss the most interesting feature the “Dynamic Programming”.
C# 4.0 introduces a new static type called dynamic (under using System.Dynamic namespace)
Dynamic objects expose members such as properties and methods at run time rather than at compile time.
At compile time the dynamic object is assumed (no static binding) to support any specified operation and it is only at runtime that the error will crop up if the concerned operation is not supported.
The type dynamic can be considered as a special version of the object type. Any object can be implicitly converted to dynamic with type checking postponed until runtime. Conversely, expressions of type dynamic can be implicitly converted to object, or any other type, as long as there exists a conversion at runtime.
For e.g.
dynamic d = 25; compile-time implicit conversion
int pp = d; runtime implicit conversion
int pp = d; runtime implicit conversion
Variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.
Dynamic operations
Method calls along with field and property accesses, indexer and operator calls ,delegate invocations and constructor calls can be dispatched dynamically:
dynamic d = GetDynamicObject(…);
d.M(7); calling methods
d.f = d.P; getting and settings fields and properties
d[“one”] = d[“two”]; getting and setting through indexers
int i = d + 3; calling operators
string s = d(5,7); invoking as a delegate
var c = new C(d); calling a constructor
d.M(7); calling methods
d.f = d.P; getting and settings fields and properties
d[“one”] = d[“two”]; getting and setting through indexers
int i = d + 3; calling operators
string s = d(5,7); invoking as a delegate
var c = new C(d); calling a constructor
The role of the C# compiler here is simply to package up the necessary information about the dynamic object d, so that the runtime can pick it up and determine needs to be done with object d.
Dynamic functionality is greatly enhanced by DLR (Dynamic Language runtime) and in fact, has been made possible because of DLR (for brief into of DLR see my earlier posts).
Part-II of the series will actually concentrate on some detailed aspects of Dynamic binding wherein I’ll cover the dynamic functionality with an elaborated example.
Hope this was Helpful.
Till next time we connect, Happy Coding!!
Comments
Post a Comment