Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add property to ExpandoObject with the same name as a string

Is there a way to add a property to an ExpandoObject with the same name as a string value?

For example, if I have:

string propName = "ProductNumber";
dynamic obj = new System.Dynamic.ExpandoObject();

I can create the property ProductNumber like:

obj.ProductNumber = 123;

But, can I create the property obj.ProductNumber based on the string propName? So, if I don't know what the name of the property will be in advanced, I can create it based on this input. If this is not possible with ExpandoObject, any other areas of C# I should look into?

like image 985
Paul Avatar asked Apr 06 '12 19:04

Paul


People also ask

How do I add property to ExpandoObject?

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

What is Expando object in C#?

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.

How do you use Expando?

To accelerate breaking time, position large diameter holes together. Make sure the holes are clean without water and residue. Pour fresh EXPANDO into holes within 10 minutes after mixing. Do not mix more than two bags (10 kg) for each lot at a time.


2 Answers

ExpandoObject implements IDictionary<string, object>:

((IDictionary<string, object>)obj)[propName] = propValue

I don't know off the top of my head whether you can use the indexer syntax with a dynamic reference (i.e., without the cast), but you can certainly try it and find out.

like image 102
phoog Avatar answered Oct 21 '22 11:10

phoog


Cast the ExpandoObject to an IDictionary<string,object> to do this:

string propName = "ProductNumber";
dynamic obj = new System.Dynamic.ExpandoObject();
var dict = (IDictionary<string,object>)obj;
dict[propName] = 123;
like image 33
BrokenGlass Avatar answered Oct 21 '22 12:10

BrokenGlass