Thursday, December 2, 2010

C# 4.0 features -- dynamic typing(1)

For this article, I am going to write what I understand so far. When I have more knowledge on dynamic, I will write more.

We write a method:

public static int GetLength(dynamic myvar)
{
return myvar.Length;
}

The dynamic keyword represents an object which will be resolved in runtime.

so in the Main entry, if we have an string object, it has Length property, we can use:

string mystring="this is for test";
int i=GetLength(mystring);

And also for an array, string[] myarr=new string[3]{"Test","Dynamic","Typing"};
array also have:
int j=GetLength(myarr);

There is no compile time error and there is no run time error.

But if we use int, it doesn't have property Length; int a=5;
int k=GetLength(a);
There is no compile time error. But in the run time, the dynamic object is resolved to int variable, and it doesn't have Length property, there will come out exception.

I wrote the following test code:

public class MyClass1
{
public int Length;
}

public class MyClass2
{ }

class Program
{
static void Main(string[] args)
{
MyClass1 myClass1=new MyClass1(){Length=3};
Console.WriteLine(GetLength(myClass1));

MyClass2 myClass2 = new MyClass2();
Console.WriteLine(GetLength(myClass2));

}

public static int GetLength(dynamic myvar)
{
return myvar.Length;
}
}

The above code explain the dynamic object, the dynamic objects are resolved to myClass1 and myClass2 respectively in the run time. In the compile time, the is no problem at all, but as myClass2 doesn't have Length property, there will have run time exception for the part: GetLength(myClass2). It will say, "RuntimeBinder exception is unhandled" as below:



The difference between "dynamic" and "var" keywords:

var is type inference, the type is determined at compile time, that means the type is determined when we assign the value to var variable.
dynamic the type is resolved at runtime, that is the dynamic type will be replaced by the actual type in run time.

Why dynamic?
To my understanding, C# is a static programming language, it do type check at compile time to improve the performance. But dynamic language such as Python which determine the type at run time. .Net 4.0 has the dynamic language runtime(DLR) which let the C# code by pass compile time type checking. So DLR can be use to programming interop with the dynamic language.
It is useful when we don't know the types in some object such as COM objects and it use IDispatch doing late binding. So C# programming in COM objects which do late binding will also have interop, and we may need to use dynamic.
Developers may use System.Reflection to do the late binding, and dynamic will from programming language to allow late binding.
And when people work on XML/HTML DOM objects, when we don't know some object types, it is needed to use dynamic.

No comments: