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

StackOverflow https://stackoverflow.com/questions/4647796

  •  09-10-2019
  •  | 
  •  

Question

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);
    }
}
Was it helpful?

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

OTHER TIPS

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);
}
try
{
    var x = Settings.Default[bonusMalusTypeKey]);
}
catch (SettingsPropertyNotFoundException ex)
{
    // Ignore this exception (return default value that was set)
}

This is how you deal with it:

if(CommonSettings.Default.Properties[str] != null)
{
    //Hooray, we found it!
}
else
{
    //This is a 'no go'
}

You could do the following:

public static void DoSomething(string str)
{
    object setting = null;

    Try
    {
        setting = CommonSettings.Default[str];
    }
    catch(Exception ex)
    {
        Console.out.write(ex.Message);
    }

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

This would ensure the setting exists - you could go a bit further and try and catch the exact excetion - e.g catch(IndexOutOfBoundsException ex)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top