Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding properties to an ExpandoObject

I would like to dynamically add properties to a ExpandoObject at runtime. So for example to add a string property call NewProp I would like to write something like

var x = new ExpandoObject(); x.AddProperty("NewProp", System.String); 

Is this easily possible?

like image 570
Craig Avatar asked Feb 08 '11 21:02

Craig


People also ask

What is System Dynamic expandoObject?

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject. sampleMember instead of more complex syntax like sampleObject.

What is dynamic properties in C#?

Dynamic objects expose members such as properties and methods at run time, instead of at compile time. This enables you to create objects to work with structures that do not match a static type or format.

What is dynamic property?

1.2 Basic Dynamic Properties and Their Significance Theoretically, it can be defined as the ratio of stress to strain resulting from an oscillatory load applied under tensile, shear, or compression mode.

How do I know if I have expandoObject property?

You can use this to see if a member is defined: var expandoObject = ...; if(((IDictionary<String, object>)expandoObject). ContainsKey("SomeMember")) { // expandoObject. SomeMember exists. }


1 Answers

dynamic x = new ExpandoObject(); x.NewProp = string.Empty; 

Alternatively:

var x = new ExpandoObject() as IDictionary<string, Object>; x.Add("NewProp", string.Empty); 
like image 137
Stephen Cleary Avatar answered Sep 28 '22 00:09

Stephen Cleary