Dynamically assign values to class instance properties / Indexing class instance properties
I have a class like:
Assuming I have a dictionary like:
Is it possible to do something like my method
FromData
?
Where if it exists, each property will be assigned the value from the dictionary?9 Replies
With reflections maybe
Could you explain?
It kinda smells of bad design tho
ehhhh
As I said, with reflections: https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/reflection-and-attributes/
It's fairly slow and inefficient, it discards the safety of the type system, but that's apparently what you want here
Alternatively, you could look into source generators
Either finding an existing one, or writing one yourself
Or, for a fairly hacky way, you could serialize the dictionary to JSON and deserialize it to a class
Which would either use reflections or source generation, depending on how you set it up
hmm this seems like a good way tbh 🤔
In general, though, C# is strictly and statically-typed. Setting properties by string name is far from the norm
Which is then just checking the properties in the class and signing them by string name 😁
This is such a hack, but I'm incredibly lazy, and it works so well lol. ty :)