I have created this dynamic object, and I want to access the properties by name:
dynamic obj = new ExpanadoObject();
obj.Name = "Reza";
What I want is
obj["Name"] = "Reza";
or
var name = obj["Name"];
How can I do that?
To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .
Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .
Check the definition of ExpandoObject
:
public sealed class ExpandoObject : IDynamicMetaObjectProvider, IDictionary<string, object>, ICollection<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, INotifyPropertyChanged
As you can see, one of the interfaces implemented by the class is IDictionary<string, object>
. Therefore, you could do this:
var dict = (IDictionary<string, object>)obj;
dict["Name"] = "Reza";
var name = dict["Name"] as string;
Note that if all you need is behavior where you access elements the dictionary-style, using ExpandoObject
is not necessary; a plain Dictionary<string,object>
would do just fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With