Last active
February 20, 2020 02:55
-
-
Save joe-oli/9a55c9bd92de82f60fd62000efefa284 to your computer and use it in GitHub Desktop.
dynamic and ExpandoObject
This file contains hidden or 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
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