views:

1658

answers:

1

I've been scouring the net for the last 3 days, and can't find any reference to this question. I've created a custom configuration class to be used with my app.config. Everything works fine. The problem comes in when a configuration property (of a configuration element) is not required, and is not defined in the app.config. It seems that default values are returned for the configuration property. Does anyone know how to determine if the property isn't defined in the app.config? (I've been trying to post my app.config, but can't figure out how to do it...anyone know how?)


//Main
namespace TestStub
{
    class Program
    {
        static void Main(string[] args)
        {
            CustomSettingsHandler config = (CustomSettingsHandler)ConfigurationManager.GetSection("CustomSettingsManager");
            Console.WriteLine("Setting1 {0}", config.Setting1.CustomSettingItem);
            Console.WriteLine("Setting2 {0}", config.Setting2.CustomSettingItem);
        }
    }
}

//Custom Configuration Class
namespace CustomConfiguration
{
    public class CustomSettingsHandler : ConfigurationSection
    {
        [ConfigurationProperty("setting1", IsRequired = false)]
        public CustomSettingElement Setting1 { get { return (CustomSettingElement)this["setting1"]; } }

        [ConfigurationProperty("setting2", IsRequired = false)]
        public CustomSettingElement Setting2 { get { return (CustomSettingElement)this["setting2"]; } }
    }

    public class CustomSettingElement : ConfigurationElement
    {
        [ConfigurationProperty("customsettingitem", IsRequired = false)]
        public int CustomSettingItem { get { return (int)this["customsettingitem"]; } }
    }
}
+1  A: 

The 2 things I can think of off the top of my head would be to use a DefaultValue, like so:

    [ConfigurationProperty("customsettingitem", DefaultValue = -1)]
    public int CustomSettingItem { get { return (int)this["customsettingitem"]; } }

Assuming there is some value that is invalid. In this case, CustomSettingItem == -1 means it wasnt set, and >= 0 was a value set in config. Of course that assumes -1 wasnt valid input in the first place.

Second idea is to use a nullable int instead:

    [ConfigurationProperty("customsettingitem", IsRequired = false)]
    public int? CustomSettingItem { get { return (int?)this["customsettingitem"]; } }

Now if nothing is set in config, it should default to null instead of 0.

rally25rs
That works, but I was hoping there was a way to suppress the default when the property is not defined. The work around I'm using right now is config.Setting2.IsPresent