Created
June 18, 2009 18:56
-
-
Save atifaziz/132122 to your computer and use it in GitHub Desktop.
Expando stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Dynamic; | |
using System.Collections; | |
using System.Runtime.CompilerServices; | |
using System.IO; | |
static class Program | |
{ | |
static void Main() | |
{ | |
dynamic obj = new ExpandoObject(); | |
// Shazam! Create proprties on the fly! | |
obj.X = 123; | |
obj.Y = 456; | |
obj.Text = "foobar"; | |
// Next, create a property that is a delegate/function. | |
obj.Add = (Func<int, int, int>) ((a, b) => a + b); | |
// Invoke Add and print results. | |
Console.WriteLine(obj.Add(obj.X, obj.Y)); | |
// Dump the object state so far. Guess what? Expando is really | |
// a dictionary so we can "reflect" on it as just key/value pairs. | |
// Casting it to IEnumerable makes sure we statically invoke Dump. | |
Dump((IEnumerable) obj); | |
// Next, we dynamically change the object. | |
// Start by taking a copy of the keys because the dictionary behind | |
// the ExpandoObject object will be modified while iterating over | |
// it, which otherwise would cause InvalidOperationException. | |
var keys = ((IDictionary<string, object>)obj).Keys.ToArray(); | |
foreach (var key in keys) | |
{ | |
// Re-write all dynamically added members by turning them into | |
// uppercase strings. | |
object value; | |
RuntimeOps.ExpandoTryGetValue(obj, null, 0, key, out value); | |
RuntimeOps.ExpandoTrySetValue(obj, null, 0, value.ToString().ToUpper(), key); | |
} | |
// Dump the new state. | |
Dump((IEnumerable)obj); | |
} | |
static void Dump<T>(T values) where T : IEnumerable | |
{ | |
Dump(values, null); | |
} | |
static void Dump<T>(T values, TextWriter output) where T : IEnumerable | |
{ | |
foreach (var value in values) | |
(output ?? Console.Out).WriteLine(value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment