michael
michael

Reputation: 15282

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

Upvotes: 17

Views: 22945

Answers (5)

salle55
salle55

Reputation: 2181

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

Upvotes: 30

ajoka
ajoka

Reputation: 61

try
{
    var x = Settings.Default[bonusMalusTypeKey]);
}
catch (SettingsPropertyNotFoundException ex)
{
    // Ignore this exception (return default value that was set)
}

Upvotes: 6

Andr&#233; Filipe
Andr&#233; Filipe

Reputation: 67

This is how you deal with it:

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

Upvotes: 5

GaryT
GaryT

Reputation: 135

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)

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245429

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

Upvotes: 6

Related Questions