How to design/write GlobalConfig class that can be inherited?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • GigaKatowice
    New Member
    • Jun 2012
    • 4

    How to design/write GlobalConfig class that can be inherited?

    Hi.

    I need to create a GlobalConfig class. But I want to derive from it in another class.

    Here's an example:

    Code:
    public class BaseConfig {
     public string GlobalPath {get; set;}
    }
    
    public class ConfigA :  BaseConfig  {
     public string pathA {get; set;}
    }
    
    public class ConfigB :  ConfigA  {
     public string pathB {get; set;}
    }
    The idea behind is that I don't want to write the code multiple times and what's more important
    in class ConfigA I want to set GlobalPath and have access to it in ConfigB.

    In other word I want class ConfigB to have a property GlobalPath which was set in class ConfigA.

    To clarify I want to have only one object of Config in memory.

    When I set BaseConf.Global Path to 'A', I want to access it from ConfigB.GlobalP ath and also get 'A'.

    I always design GlobalConfig as a static class, but static classes can't be inherited.
    So I tried to implement Singleton Pattern, but ConfigA can't find constructor of class BaseConfig because
    it's private.

    I'll appreciate all help and suggestions.
    Thank you.
  • Joseph Martell
    Recognized Expert New Member
    • Jan 2010
    • 198

    #2
    Instead of using the automatically generated property syntax, try creating a property in your ConfigBase class that refers to a private static member. There is no rule that says you have to refer to an instance member when using an instance property.

    Something along the lines of this:

    Code:
        public abstract class TestBase
        {
            private static string _path;
    
            public string Path
            {
                get { return _path; }
                set { _path = value; }
            }
        }
    
        public class TestA
            : TestBase
        { }
         
        public class TestB
            : TestBase
        { }
    Now the path should be the same between all instances of TestA and TestB and because TestBase is declared as abstract it cannot be instantiated directly.

    Comment

    Working...