The ExpandoObject is actually pretty cool in C#. The dynamic keyword is actually pretty powerfull but might give you some Runtime Errors.
var vs. dynamic keyword:
If you use the dynamic keyword, the type is decided at runtime. When using the var keyword, the compiler checks which type should be used when building/compiling.
I wrote a little example so that you could see the ExpandoObject and the dynamic keyword in action:
using System;
using System.Dynamic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
dynamic _MyDog = new ExpandoObject();
_MyDog.BarfEvent = null;
_MyDog.BarfEvent += new EventHandler(OnBarf);
_MyDog.Name = "Lassie";
_MyDog.Age = "3";
_MyDog.Family = new ExpandoObject();
_MyDog.Family.Father = "Tramp";
_MyDog.Family.Mother = "Lady";
_MyDog.FavoriteFood = new string[2];
_MyDog.FavoriteFood[0] = "Cats";
_MyDog.FavoriteFood[1] = "Sausages";
_MyDog.Barf = new Action(() =>
{
Console.WriteLine("Bark Bark!");
// calling the event
EventHandler tmp = _MyDog.BarfEvent;
if (tmp != null)
tmp(_MyDog, new EventArgs());
});
// testing everything
Console.WriteLine(_MyDog.Name);
Console.WriteLine(_MyDog.Age);
Console.WriteLine(_MyDog.Family.Father);
Console.WriteLine(_MyDog.Family.Mother);
Console.WriteLine(_MyDog.FavoriteFood[0]);
Console.WriteLine(_MyDog.FavoriteFood[1]);
_MyDog.Barf();
Console.ReadLine();
}
public static void OnBarf(object sender, EventArgs e)
{
Console.WriteLine("I barked");
}
}
}
Enjoy
Pingback: C# Expression Trees | Teusje
Pingback: PowerGen Power-U Dual Port USB Car Charger charges your iPad, iPhone, iPod, HTC, Blackberry, MP3 Players, Digital Cameras, PDAs, Mobile Phones.