public abstract class BaseConfigurationSection<T> : ConfigurationSection where T : ConfigurationSection, new() { public static T Open() { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (config.Sections[typeof(T).Name] == null) { T instance = new T(); config.Sections.Add(typeof(T).Name, instance); config.Save(ConfigurationSaveMode.Full); } return config.Sections[typeof(T).Name] as T; } public void Save() { Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); T section = (T)configuration.Sections[typeof(T).Name]; CopyProperties(this, section); configuration.Save(ConfigurationSaveMode.Full); } private static void CopyProperties(ConfigurationElement source, ConfigurationElement destination) { foreach (PropertyInfo property in source.GetType().GetProperties()) { if (property.IsDefined(typeof(ConfigurationPropertyAttribute), false)) { if (typeof(ConfigurationElement).IsAssignableFrom(property.PropertyType)) { CopyProperties( (ConfigurationElement)property.GetValue(source, null), (ConfigurationElement)property.GetValue(destination, null)); } else { object value = property.GetValue(source, null); property.SetValue(destination, value, null); } } } } }Using this a base class you can then create your own custom sections as shown below
public class MySection : BaseConfigurationSection<MySection> { public MySection() { } [ConfigurationProperty("Destination", DefaultValue = "Some place", IsRequired = true)] public string Destination { get { return (string)this["Destination"]; } set { this["Destination"] = value; } } [ConfigurationProperty("DialCode", DefaultValue = "01932", IsRequired = true)] public string DialCode { get { return (string)this["DialCode"]; } set { this["DialCode"] = value; } } }All this seems to work fine, but I want to inherit from "MySection" and am unsure as to how to do it - I've tried the normal way of subclassing
class MySection2:MySection
{
}
but get errors about cannot implicitly convert MySection to MySection2 and so on - is what am trying possible ?