1

pseudo code:

using wLog.Properties;

var sName = frmControlProp[cn].SettingName;  
var pSettings = Properties.Settings.Default + sName;  

sName value equals, for example, Password. I would like pSettings to equal Properties.Settings.Default.Password
How do I achieve this?

dottedquad
  • 1,371
  • 6
  • 24
  • 55
  • Oh, do you want to get dynamically the property? If so you have to use [reflection](http://stackoverflow.com/questions/2762531/c-sharp-reflection-and-getting-properties). – glautrou Aug 16 '13 at 16:49

3 Answers3

2

You can't write code exactly like you want and there is no syntactic sugar to get you close to desired syntax.

This usually achieved by using dictionary. Not sure what type of Deafult is but assuming it is some sort of IDictionary code would look like:

var pSettings = Properties.Settings.Default[settingName];  

Another option is to use reflection and get property by name - Get property value from string using reflection in C#, sample from that question:

public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

 var pSettings = (string)GetPropValue(Properties.Settings.Default, settingName);
Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
1

Properties.Settings.Default will return an instance of Properties.Settings which will be a subclass of ApplicationSettingsBase. That has an indexer with a string key, so you can use:

string name = frmControlProp[cn].SettingName;
object setting = Properties.Settings.Default[name];

Note that if you know (and want to use) the type of the setting you're interested in, you'll need to cast. For example:

string setting = (string) Properties.Settings.Default[name];

Also note that if the setting doesn't exist, a SettingsPropertyNotFoundException will be thrown. You can use the PropertyValues property to fetch all the values and check for the presence of the one you're interested in.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Use a reflection

Look at the Type Class

using wLog.Properties;

var sName = frmControlProp[cn].SettingName;

var type = Properties.Settings.Default.GetType();
var pSettings = type.GetField(sName).GetValue(Properties.Settings.Default);
AndrewK
  • 717
  • 5
  • 11