C #: How to make sure that a settings variable exists before trying 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); } } 
+8
c # settings settings.settings
source share
5 answers

Depending on what type of CommomSettings.Default , a simple zero check should be in order:

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

If you want to check before trying to get this parameter, you need to publish Type of CommonSettings.Default. This is like a dictionary so you can leave:

 if(CommonSettings.Default.ContainsKey(str)) { DoSomethingElse(CommonSettings.Default[str]); } 
+5
source share

If you use SettingsPropertyCollection , you need to go in cycles and check which settings exist themselves, it seems, since there is no Contains method in it.

 private bool DoesSettingExist(string settingName) { return Properties.Settings.Default.Properties.Cast<SettingsProperty>().Any(prop => prop.Name == settingName); } 
+15
source share
 try { var x = Settings.Default[bonusMalusTypeKey]); } catch (SettingsPropertyNotFoundException ex) { // Ignore this exception (return default value that was set) } 
+6
source share

Here's how you handle it:

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

You can 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 will provide customization - you can go a little further and try and catch the exact excetion - for example, catch (IndexOutOfBoundsException ex)

0
source share

Source: https://habr.com/ru/post/650876/


All Articles