Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to Dynamic object properties by name

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?

like image 586
Reza Avatar asked Mar 15 '16 21:03

Reza


People also ask

How do you dynamically access object property in TypeScript?

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] .

How do you access the properties of an object with a variable?

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] .


1 Answers

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.

like image 135
Sergey Kalinichenko Avatar answered Oct 19 '22 17:10

Sergey Kalinichenko