2

Is it possible to build dynamic objects having the property name set to the value of a variable?

for instance this seems standard...

dynamic elem = new Object();
elem.Name = "myName";

but how would this be implemented?...

string fn = "FirstName";
string ln = "LastName";
dynamic elem = new Object();
elem.fn = "John";
elem.ln = "Doe";

where as i would be able to call the properties like...

string fn = elem.FirstName;
5
  • msdn.microsoft.com/en-us/library/… Commented Jul 27, 2017 at 22:19
  • thanks, I tried that earlier but... "Additional information: Cannot apply indexing with [] to an expression of type 'object'". Not dealing with a dictionary here. The dynamic Object could have many properties, not just a key and a value. Commented Jul 27, 2017 at 22:20
  • for instance this seems standard... No It can not work, object doesn't have a property Name..... Post compilable/correct code Commented Jul 27, 2017 at 22:23
  • Why do you want to do this? Commented Jul 27, 2017 at 22:24
  • There is not a mechanism in C# to macro-replace member names. Seems like an indexer is the most appropriate solution, which means you can use a simple Dictionary<string,object>. If that does not meet your needs then please add to your question, but the syntax you propose is not possible in C#. Commented Jul 27, 2017 at 22:32

1 Answer 1

6

The ExpandoObject also implements IDictionary<string, object>, meaning you can add properties using a string key.

dynamic person = new ExpandoObject();

person.FirstName = "Alex";
var ln = "lastname";

(person as IDictionary<string, Object>)[ln] = "KeySmith";
Sign up to request clarification or add additional context in comments.

1 Comment

I've noticed a -1, any feedback would be a appreciated. Of course making use of dynamic / expandobject should be carefully considered, however I believe this is answering the question at hand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.