Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.

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

Here's an example:

C#
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.GlobalPath to 'A', I want to access it from ConfigB.GlobalPath 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.
Posted
Updated 31-Jan-13 0:22am
v3

1 solution

Change the private constructor to protected.

Good luck!
 
Share this answer
 
Comments
GigaKatowice 31-Jan-13 6:19am    
Hi. Changing private to protected allowed me to compile my code, but my solution doesn't work like I want. To clarify I want to have only one object of Config in memory.

When I set BaseConf.GlobalPath to 'A', I want to access it from ConfigB.GlobalPath and also get 'A'.
E.F. Nijboer 31-Jan-13 7:13am    
In that case you need encapsulation instead of inheritance. Meaning both classes use the (static) singleton class but do not inherit from it. Inheritance will create two instances and therefor also will create an instance of everything inherited from BaseConfig. Inheritance will only work for code reuse and in this case you want to share instance data.
GigaKatowice 1-Feb-13 4:24am    
Hi. You are right. I tried solution with inheriting from singleton, but I get two instances of BaseConfig. One for BaseConfig itself, and second for ConfigA instance.

Maybe you can give an example of your idea, because I have no idea how to implement your solution.

Thank you for all your help.
E.F. Nijboer 1-Feb-13 5:03am    
It is actually quite simple. When you now inherit ConfigA and ConfigB from BaseConfig, it will use GlobalConfig for every instance.

public static class GlobalConfig {
public static string GlobalPath {get; set;}
}

public class BaseConfig {
public string GlobalPath {
get {
return GlobalConfig .GlobalPath;
}
set {
GlobalConfig .GlobalPath = value;
}
}
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900