C# 4.0 Feature - Dynamic Keyword

Lets look into new C# 4.0 feature, “Dynamic” keyword. In the past we always used to type cast objects to a particular object or datatype if the available value is of another type. For eg:
We have created a Employee Class
public class Employee
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
}

Now we have a InitilaizeEmployees() method, which has a written type as object
public object InitializeEmployee()
{
Employee emp = new Employee();
emp.EmployeeID = 1;
emp.EmployeeName = "Jack";
return emp;
}

Now if we had to assign the object “obj” to a employee object we had to type cast with “Employee” for eg: If we write
Employee emp = InitializeEmployee();
We will get a compile type error, since it is not of the same type hence we will have to write as
Employee emp =(Employee) InitializeEmployee();

To ease this we have a new keyword known as “Dynamic” where we can replace the above code as
dynamic emp = InitializeEmployee();

This is achieved by the “Dynamic Language Runtime”.
Now if we try “emp. “, the intellisence don’t work and states “This Operation will be resolved at runtime”. We don’t have to worry and continue with the property name and do what needs to be done.

Hope this was cool feature. Please add your comments or suggestions.

Cheers!!!

Comments

Popular posts from this blog

Jesus - God Thinks of you.

ASP.NET 4.0 Feature - URL Routing

Tips on JQuery Intellisense in VS 2008