Search code examples
c#properties.settings

using a variable to assign a property in c#?


I have some properties set in the settings of a c# application. I am using them to store a string. My problem is i want to call them based on the name variable of the class.

So i want to do something like this

Description = Properties.Settings.Default.(name + "Description");

Is this possible? Or do i have to write a nasty switch statement based off the the name property?

Swith(name)
case:name1 
 Description = properties.settings.default.name1Descrition;

Solution

  • Assuming you are talking about Winforms, Properties.Settings.Default is an indexable collection, so you just need to get it by key:

    var Description = Properties.Settings.Default[name + "Description"] as string;
    

    You don't need to use reflection, it is retrievable either way. You are close in your first guess.

    Using the indexer to get the value always returns an object so you need to cast it to the final type (the as string) or whatever type the property is.