❔ how to set a dynamic's property of a unknown name
if i have var dyn = new dynamic
and i have string variableName = "toto"
how can i set dyn.variableName = "hello"
for example.
the thing is variableName could be anything and I then want to be able to access it by calling for example dyn.toto if that was the name used for that property
16 Replies
If you are 100% sure you need this, you could take a look at https://learn.microsoft.com/en-us/dotnet/api/system.dynamic.expandoobject?view=net-7.0
It really depends on if you are controlling the creation of the object. If you are getting an object passed in that you don't control, you probably should look into Reflection and not dynamic.
In general... Likely a bad idea, but there are 1 in 10000000 situations where it has legit use 😄
But if it's just curiosity, then expando-object it is
i didnt see in the expando docs anywhere where they create a property with a variable name
You might want a dictionary instead
lol yea dictionary might be the way to go
With a dictionary, you could do
dict["todo"] = something;
and then dict["todo"]
to get the valueyea, i was starting to fall into a pit of toughts but yea dictionary should do the trick
that's what expandoobject is internally
IDictionary<string, dynamic>
, i thinkC# Online Compiler | .NET Fiddle
Test your C# code online with .NET Fiddle code editor.
that, but yeah it's really just a dictionary
Ero#1111
REPL Result: Success
Result: ValueTuple<object, object>
Compile: 496.572ms | Execution: 100.436ms | React with ❌ to remove this embed.
alright thanks
So you'd do it like this with expando, as I think the interface impl is explicit for IDictionary
The key is, you can use it like a dictionary, but you have to explicitly cast it to an
IDictionary<string, object>
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.