Wednesday, June 15, 2011

Dynamic keyword – What’s new in C# 4.0

Dynamic keyword is introduced in C# 4.0. Dynamic operations are checked at runtime not at compile time. This is also known as Duck Typing (A style of dynamic typing). No IntelliSense available with dynamic type (when you press ‘.’) because dynamic type will be resolved at runtime. You can data bind dynamic object. You can go through my separate post for more information about binding dynamic object here.

The Dynamic Language Runtime (DLR) provides infrastructure to support dynamic type in C#. It also provides implementation of dynamic programming language such as IronPython and IronRuby so from C# application you can talk with dynamically typed programming languages like Python and Ruby.   

You can use dynamic as type in Property, Method parameters, Indexer, return value etc. Please see below examples.

dynamic d = 25;
Console.WriteLine(d.GetType().ToString()); //GetType checked at runtime.


public class Employee
    public string EmployeeName { get; set; }
    public int EmployeeAge { get; set; }
    public Employee(string name, int age)
        EmployeeName = name;
        EmployeeAge = age;
    public string GetEmployeeDetails()
        return EmployeeName;

dynamic d = new Employee("Mitesh", 29);
Console.WriteLine(d.GetEmployeeDetails()); //GetEmployeeDetails() method checked at runtime.
Console.WriteLine(d.GetDepartment()); //gives runtime error bcoz no method available named GetDepartment in Employee class



You can’t use Lambda expression / LINQ queries as an argument to dynamic object.

dynamic colleciton = new List<string>();
var result = colleciton.Select(str => str + ","); //compile time error

var strCollection = from string s in colleciton
                    select s;  //compile time error

No comments:

Post a Comment