Search code examples
c#settingssettings.settings

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


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);
    }
}

Solution

  • Depending on what type CommomSettings.Default is, a simple null check should be fine:

    if(setting != null)
        DoSomethingElse(setting);
    

    If you want to check BEFORE trying to retrieve the setting, you need to post the Type of CommonSettings.Default. It looks like a Dictionary so you might be able to get away with:

    if(CommonSettings.Default.ContainsKey(str))
    {
        DoSomethingElse(CommonSettings.Default[str]);
    }