C#: How to make sure a settings variable exists before attempting to use it from another assembly?

michael picture michael · Jan 10, 2011 · Viewed 19.9k times · Source

I have the following:

using CommonSettings = MyProject.Commons.Settings;

public class Foo
{
    public static void DoSomething(string str)
    {
        //How do I make sure that the setting exists first?
        object setting = CommonSettings.Default[str];

        DoSomethingElse(setting);
    }
}

Answer

salle55 picture salle55 · Jan 9, 2014

If you are using a SettingsPropertyCollection you have to loop and check which settings exists yourself it seems, since it doesn't have any Contains-method.

private bool DoesSettingExist(string settingName)
{
   return Properties.Settings.Default.Properties.Cast<SettingsProperty>().Any(prop => prop.Name == settingName);
}