The new Dynamic type in .NET 4.0 looks quite interesting. Not like .NET 3.5 dynamic variable (var keyword) which is static type inference by compiler, Dynamic objects are run-time behavior. Following code example is copied from MSDN documentation, and comments are removed for brevity reason:
using System;The result is:
using System.Collections.Generic;
using System.Dynamic;
public class DynamicDictionary : DynamicObject
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
public int Count { get { return dictionary.Count; }}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
string name = binder.Name.ToLower();
return dictionary.TryGetValue(name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
dictionary[binder.Name.ToLower()] = value;
return true;
}
}
class Program
{
static void Main(string[] args)
{
dynamic person = new DynamicDictionary();
person.FirstName = "Ellen";
person.LastName = "Adams";
Console.WriteLine(person.firstname + " " + person.lastname);
Console.WriteLine( "Number of dynamic properties:" + person.Count);
Console.Read();
}
}
Ellen Adams
Number of dynamic properties:2