Skip to content

Instantly share code, notes, and snippets.

@joe-oli
Last active February 20, 2020 02:55
Show Gist options
  • Save joe-oli/9a55c9bd92de82f60fd62000efefa284 to your computer and use it in GitHub Desktop.
Save joe-oli/9a55c9bd92de82f60fd62000efefa284 to your computer and use it in GitHub Desktop.
dynamic and ExpandoObject
dynamic x = new ExpandoObject();
x.NewProp = string.Empty;
Alternatively:
var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);
//=============
IDictionary<string, object> expando = new ExpandoObject();
expando["foo"] = "bar";
dynamic d = expando;
Console.WriteLine(d.foo); // bar
//Example use case, convert XML payload. loop over the elements, e.g.
var doc = XDocument.Load(file);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var element in doc.Root.Elements())
{
expando[element.Name.LocalName] = (string) element;
}
//================================
//helper class which converts an Object and returns an Expando with all public properties of the given object;
//useful when you want to augment an object with more props
public static class dynamicHelper
{
public static ExpandoObject convertToExpando(object obj)
{
//Get Properties Using Reflections
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = obj.GetType().GetProperties(flags);
//Add Them to a new Expando
ExpandoObject expando = new ExpandoObject();
foreach (PropertyInfo property in properties)
{
AddProperty(expando, property.Name, property.GetValue(obj));
}
return expando;
}
public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
{
//Take use of the IDictionary implementation
var expandoDict = expando as IDictionary;
if (expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
else
expandoDict.Add(propertyName, propertyValue);
}
}
//Usage:
//Create Dynamic Object
dynamic expandoObj= dynamicHelper.convertToExpando(myObject);
//Add Custom Properties
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment