Wednesday, June 10, 2009

Dynamic Programming With .Net Framework 4.0 and C#

Microsoft have introduced new Dynamic Language Runtime with framework 4.0 . This API supports a new type dynamic which enables dynamic features in statically typed language like C#.

Below are two important findings about dynamic type from MSDN.

1. The type dynamic is a static type but an object of type dynamic bypasses compile time checking.

2.At compile time dynamic variables are compiled into variables of type object.Therefore, type dynamic exists only at compile time not at runtime.

As all of you will find everything detail in MSDN I am Jumping into the code directly.

For the sake of simplicity to show how the dynamic type works in C# I am declaring a naive class MyDateTime which is a skeleton of the .Net Type DateTime.


public class MyDateTime
{
public int Month
{
get { return dateTime.Month;}
}
public int Year
{
get { return dateTime.Year; }
}
public int Day
{
get { return dateTime.Day; }
}


private DateTime dateTime;

public MyDateTime()
{
dateTime = new DateTime();
}

public MyDateTime(int day, int month, int year)
{
dateTime = new DateTime(year, month, day);
}

public override string ToString()
{
return dateTime.ToString("MM/dd/yyyy");
}

public void AddDays(int numberOfDays)
{
dateTime = dateTime.AddDays(numberOfDays);
}
}

Now we can use it like

dynamic dateTime = new MyDateTime(6,9,2009);
Console.WriteLine("Date:{0} ",dateTime);
Console.WriteLine("Month:{0}",dateTime.Month);
Console.WriteLine("Day{0}:",dateTime.Day);
Console.WriteLine("year:{0}",dateTime.Year);


No compile time type checking will occur for the variable dateTime in the above WriteLine methods.

We can also call AddDays function of MyDateTime object through the dynamic type variable dateTime

dateTime.AddDays(7);


But one drawback with this dynamic thing is that you can call any method or access any property which is not actually present in the statically typed object.

So if we call a method SubtractDays for our early dateTime variable

dateTime.SubtractDays(7)

it will not signal us any error at compile time. But at runtime we will fell trap of RuntimeBinderException saying 'MyDateTime does not contain a defination for SubtractDays'.

Reference: MSDN

1 comment:

  1. The example is good but looks clumsy.If you use something for code representation it will be more helpful.

    ReplyDelete