C# 4.0 provides access to the Dynamic Language Runtime (DLR) using the new ‘dynamic’ keyword in .NET4, allowing dynamic languages like Ruby and Python to expose their objects to C#. Apart from consuming objects from dynamic languages, this feature also helps us in implementing customized dynamically dispatched objects. This can be done by implementing the IDynamicObject interface, which itself is usually done by inheriting from the abstract DynamicObject class and providing our own implementation and invocation; the IDynamicObject interface allows us to interoperate with the DLR and implement our own behavior!
Before we can go into what Dynamic type is and how it acts, we need to have a basic understanding about DLR and its components, so we’re going to spend a bit of time investigating this new feature.
Dynamic Language Runtime (DLR)
The DLR is the new API in .NET Framework 4 that is responsible for implementing dynamic programming, and is common runtime for the dynamic languages. The C# runtime is built on the top of the DLR in order to give provision for the dynamic typing. The below figure illustrates the block diagram of the DLR and its internal components.
Fig 1: C#4.0 dynamic programming, and how DLR works.
The languages with dynamic capabilities (such as C#4.0 and VB 10.0) are built on top of the DLR which, as we can see above, has three main components at it’s core:
1. Expression Trees
2. Dynamic Dispatch
3. Call Site Caching
An Expression Tree depicts code in the form of a tree, which allows languages to be translated into a standard design on which the DLR can operate. These are the same kind of expression trees that were introduced in C# 3 LINQ, but which have now been improved to support statements. Once code is in a tree representation, the DLR can take the tree and use it to generate CLR code.
Dynamic Dispatch is the process of mapping messages to sequences of code at runtime . This is the way that the system lets the binders decide on the target method. Code is generated for dynamic invocations to the appropriate Language Binders.
Call Site Caching is used to avoid the need to call into the binder. Normally the binder returns an expression tree which the DLR compiles, but this step can be avoided if the types of the arguments are the "same".
Speaking of the binders, these exist beneath the DLR, and are responsible for communicating with the respective environments of different technologies. For example, the Object binder allows communication with .NET Objects, the JavaScript binder allows communication with JavaScript in Silverlight, the Python and Ruby binders allow to communication with their respective languages, and the COM binder allows communication with Office / COM Objects.
All of this is wrapped up in the DLR, which C# 4.0 provides access to using the new ‘dynamic’ keyword. This permits data types to be decided dynamically at runtime, as opposed to statically at compile-time, by redirecting any calls involving a parameter of type dynamic through the DLR. Dynamic type signifies to the compiler that all operations based on that type should (unsurprisingly) be inferred dynamically, and instructs the compilerto ignore the compile time checking for this type.
The C# compiler now allows for calling a method with any name and any arguments on dynamically created object types. Consider the code below.
dynamic d = GetNum();
d.divide(40,5); // allows us to call any method with any signature..
As d is declared as dynamic, the compiler will not generate any runtime errors for the above declaration and, although it will still engage in type checking, it will not decide the target data type of the call until runtime; so the actual object that is being dynamically referred to will be determined at runtime. As mentioned in the code annotation above, the compiler allows calling dynamic objects with any method or signature.
Because C# is a statically typed language, the ‘dynamic' type informs the compiler that it is working with a dynamic invocation, and so can forget about the normal compile-time checking for that type. However, this also means that illegal operations (if any) will only be detected at runtime.
The Difference between Var and Dynamic
People often get confused between var and dynamic, so I would like to you to understand exactly what is meant by each keyword.
If the ‘var’ keyword is used, the data type is still determined by the compiler at compile time. On the other hand, when the ‘dynamic’ keyword is used, the member and method lookups are determined at runtime. In addition, dynamic can also be used as the return type for methods, and the Var keyword cannot be used for procedure return calls.
In addition, the dynamic keyword will not give you trouble if it doesn't have any associated method. On the other hand, var will never allow the application to compile if any method is used which is not associated with it.
An Example of Dynamic
static void Main(string[] args)
{ var d = new Math();
Console.WriteLine(d.Add(10, 20) + " -- Calls the int version. "+ "\n" +// Calls the //int version.
d.Add("abc", "def") + " -- Calls the string version" + "\n" +// Calls the string
// version.
d.Add((object)10, (object)20) + " -- Calls the integer version " + "\n" +// Calls the
// integer version.
d.Add((object)"abc", (object)"def") + " -- Calls the object version " + "\n" +// Calls
// the object version.
d.Add((dynamic)10, (dynamic)20) + " -- Calls the int version " + "\n" + // Calls the
// int version
d.Add((dynamic)"abc", (dynamic)"def") + " -- Calls the string version "); // Calls the
// string version.
Console.WriteLine(d.Multiply(10, 20)); ;
Console.ReadLine();
}
public class Math : Program
{
///
/// The method a returns Dynamic type that can be used to pass the objects of any
/// datatype.
/// The parameters get added and returned dynamically at runtime.
/// The data type is decided at runtime as the dynamic datatype gets assigned at
/// runtime.
///
///
///
///
dynamic Add(dynamic a, dynamic b)
{
return a + b;
}
///
/// This method is used for multiplying the numbers. We need not declare 2
/// separate methods for different datatypes (integer and double).
/// The dynamic data type gets assigned at runtime.
///
///
///
///
dynamic Multiply(dynamic a, dynamic b)
{
return a * b;
}
}
In the above example, parameters a and b are dynamic, and so their runtime data types are used to resolve the method. If we are doing subtraction, multiplication and division operations, then using Dynamic type really saves time, as we do not need to create separate methods for each data type, like integer and double. However, make sure that you pass valid data type values, otherwise runtime errors will still be thrown. For example, you cannot use string data types for the division operator, as this is clearly illegal.
Although Dynamic is really just hiding the use of reflection under the hood, Dynamic produces the same code created by the compiler, and so has a advantage over reflection when you need dynamic access to objects at runtime. For example, consider the code below that is used to get Authors from a publisher, and which uses reflection to invoke the GetAuthor () method:
//Before dynamic
object publisher = GetPublisher();
Type pubtype = publisher.getType();
object pubObj = pubtype.InvokeMember("GetAuthor", BindingFlags.InvokeMethod, null, new
object [] {}); //use reflection to invoke the method
string author = pubObj.ToString();
This can now be written as the code below, using the dynamic keyword:
//With dynamic:
dynamic publisher = GetPublisher();
string author= publisher.GetAuthor();
The Dynamic type is also very helpful when interoperating with Office Automation API’s, which saves you from casting everything from the object. Finally, to finish off this look at the capabilities of the dynamic data type, bear in mind that it can be applied not only to method calls, but also for several other operations:
- Field and property accesses,
- Indexer and operator calls,
- Delegate invocations and constructor calls.
Limitations
- The Dynamic keyword cannot be used for the Class base type.
- The Dynamic keyword cannot be used with the Operator type.
- Extension methods cannot be used dynamically; Extension methods are introduced for the ability to add the assembly which contains the extension via a using clause. This is available at compile time for method resolution, but not at runtime; hence, dispatching to the extension method at runtime is not supported.
- LINQ relies completely on extension methods to perform query expression operation, but extension methods cannot be resolved at runtime due to the lack of information in the compiled assembly. Hence, using LINQ Queries over dynamic objects is problematic.
- Anonymous functions cannot be used as parameters, as the compiler cannot bind an anonymous function without knowing the type it is converting
- A lambda expression cannot be passed in extension methods as an argument to a dynamic operation.
- A dynamic object's type is not inferred at the compile time of an operation, so if any error occurs, it will be identified only at runtime. Static or strongly typing is not maintained in the case of dynamic, and the introduction of dynamic C# opens the doors for duck typing.
- Additionally, the result of any dynamic operation is itself of type dynamic, with the two exceptions:
- The type of a dynamic constructor call is the constructed type; for example, the type of demo in the following declaration is Demo Class, not dynamic.
var demo = new Demo(d);
- The type of a dynamic implicit or explicit conversion is the target type of the conversion.
Optional Parameters
Microsoft’s coevolution in C# and VB languages has made this feature possible now. These parameters need to be declared with a default value in the method signature, and allow for omitting arguments to member invocations. The below example describes the syntax:
private void CreateNewStudent(string name, int studentid = 0, int year = 1)
Note: The Optional Parameters must be placed after the required parameters, or else the C# compiler will show a compile time error.
There are a few limitations to the optional parameters feature, and we’ll look at them after we’ve considered the new Names Arguments feature, as the two are very useful when deployed together.
Named Arguments
Named arguments are a way to provide an argument using the name of the desired parameter, instead of depending on its [the parameter’s] position in the parameter list. Now, if we want to omit the OrderId parameter value in the above code, but specify the year parameter, the new named arguments feature (highlighted below) can be used. All of the following are also valid calls:
CreateOrders(OrderId:2AS34, OrderName:"Demo");
4. Generic Variance
The term "variance" refers to the ability to use one type where another was specified, and in that context there are 3 terms we need to become familiar with:
Invariant: A return parameter is invariant if we must use the exact match of the type name between the runtime type and declared type. For invariant parameters, neither covariance nor contravariance is permitted
Covariant: A parameter is covariant if we can use a derived type as a substitute for the parameter type, and a derived class instance can be used where a parent class instance was expected. Covariance is the conversion of a type from more specific to more general. For example, converting an object of type car to the type automobile.
Contravariant: Contravariance is exactly the opposite of Covariance, i.e. it is the conversion of a type from more general to more specific. A return value is contravariant if we can assign the return type to a variable of a less derived type than the parameter. A base class instance can be used where a subclass instance was expected.
- Variance is a property of operators that act on types. It is the concept of specifying in and out parameters on generic types and allowing assignments where it is safe.
- Variant type parameters can be declared for interfaces and delegate types.
Generic parameters in interfaces are invariant by default., so we need to explicitly specify whether we need a particular generic parameter to be covariant or contravariant. The example below demonstrates both co-variance and contra-variance support in C# 4.0:
class Fruit { }
class Apple : Fruit { }
class Program
{
delegate T Func<out T>();
delegate void Action<in T>(T a);
static void Main(string[] args)
{
// Covariance
Func<Apple> apple = () => new Apple();
Func<Fruit> fruit = apple;
// Contravariance
Action<Fruit> fru1 = (fru) =>
{ Console.WriteLine(fru); };
Action<Apple> app1 = fru1;
}
}
Covariant parameters will only be used in output positions: method return values, get-only properties or indexers, and Contravariant parameters will only occur in input positions: method parameters, set-only properties or indexers.
Additionally, the generic variance feature also allows the assignment of the object type IEnumerable