Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get dynamic property from Settings

I've got a few properties stored in my AppConfig and now I want to access them dynamically (e.g. in a loop or function).

Accessing the values using MySettings.NAME_OF_THAT_THING is no problem, but what if the name is variable?

I tried:

String propertyValue = MySettings.GetType().GetProperty("NAME_OF_THAT_THING").ToString();

But the only thing I got back is the name of the property. How can I do this?

like image 692
user1450661 Avatar asked Jun 12 '12 12:06

user1450661


2 Answers

All you need to do is:

String propertyValue = Settings.Default["NAME_OF_THAT_THING"].ToString();

While using reflection will obviously work, it's overkill.

like image 71
Steven Doggart Avatar answered Sep 22 '22 04:09

Steven Doggart


String propertyValue = MySettings.GetType()
.GetProperty("NAME_OF_THAT_THING")
.GetValue(MySettings, null); //replace MySettings with null in GetValue(...) if MySettings is  a static class
like image 40
Raphaël Althaus Avatar answered Sep 19 '22 04:09

Raphaël Althaus