I have the following:
using CommonSettings = MyProject.Commons.Settings;
public class Foo
{
public static void DoSomething(string str)
{
//How d
try
{
var x = Settings.Default[bonusMalusTypeKey]);
}
catch (SettingsPropertyNotFoundException ex)
{
// Ignore this exception (return default value that was set)
}
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]);
}
This is how you deal with it:
if(CommonSettings.Default.Properties[str] != null)
{
//Hooray, we found it!
}
else
{
//This is a 'no go'
}
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);
}
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)