C
C#2y ago
PatrickG

❔ 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
LPeter1997
LPeter19972y ago
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
Axiss
Axiss2y ago
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.
LPeter1997
LPeter19972y ago
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
PatrickG
PatrickGOP2y ago
i didnt see in the expando docs anywhere where they create a property with a variable name
Thinker
Thinker2y ago
You might want a dictionary instead
PatrickG
PatrickGOP2y ago
lol yea dictionary might be the way to go
Thinker
Thinker2y ago
With a dictionary, you could do dict["todo"] = something; and then dict["todo"] to get the value
PatrickG
PatrickGOP2y ago
yea, i was starting to fall into a pit of toughts but yea dictionary should do the trick
ero
ero2y ago
that's what expandoobject is internally IDictionary<string, dynamic>, i think
Axiss
Axiss2y ago
C# Online Compiler | .NET Fiddle
Test your C# code online with .NET Fiddle code editor.
Axiss
Axiss2y ago
that, but yeah it's really just a dictionary
MODiX
MODiX2y ago
Ero#1111
REPL Result: Success
dynamic expando = new ExpandoObject();
expando.Foo = "Bar";
expando.Qux = 123;

(expando.Foo, expando.Qux)
dynamic expando = new ExpandoObject();
expando.Foo = "Bar";
expando.Qux = 123;

(expando.Foo, expando.Qux)
Result: ValueTuple<object, object>
{
"item1": "Bar",
"item2": 123
}
{
"item1": "Bar",
"item2": 123
}
Compile: 496.572ms | Execution: 100.436ms | React with ❌ to remove this embed.
PatrickG
PatrickGOP2y ago
alright thanks
LPeter1997
LPeter19972y ago
LPeter1997
LPeter19972y ago
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>
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server