In other languages like JavaScript I can use for example:
const obj = { a: 5 };
obj["a"] //returns 5
Is it possible to get an object property if it's name is given as string in C#? I don't want a giant if/else tree
You can use reflection:
var obj = new { A = 5 } as object; // your object
var five = obj.GetType().GetProperty("A").GetValue(obj);
Also, you can use dynamic:
var fiveDynamic = (obj as dynamic).A;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With