Last Updated: February 25, 2016
·
288
· frockenstein

C# Expando Fun

One of the cooler things I've seen with the .Net Framework has been how you can use ExpandoObjects for all sorts of things. Coming from a guy who likes the flexibility of Python or JavaScript, this sort of thing warms my heart.

// you'll need to ref System.Dynamic
dynamic d = new System.Dynamic.ExpandoObject();

d.MyEvent = null; // needs to be initialized this way before assignment
d.MyEvent += new EventHandler((sender, args) => Console.WriteLine("event one"));
d.MyEvent += new EventHandler((sender, args) => Console.WriteLine("event two"));

d.Console = new Action(() => Console.WriteLine("action!"));
d.Multiply = new Func<int, int>((i) => i * i);

d.Prop = "string property";
Console.WriteLine(d.Prop);
d.Prop = 1;
Console.WriteLine(d.Prop);

EventHandler e = d.MyEvent;
e(d, EventArgs.Empty);
d.Console();
Console.WriteLine(d.Multiply(2));