Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# get Object Property by name [duplicate]

Tags:

c#

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

like image 601
Zer0 Avatar asked Oct 30 '25 07:10

Zer0


1 Answers

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;
like image 134
Dilshod K Avatar answered Oct 31 '25 20:10

Dilshod K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!