I need to create a GlobalConfig class. But I want to derive from it in another class.
Here's an example:
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.
VulpesPosted Feb 1, 2013, 10:45 AM
using System;
public abstract class BaseConfig
{
public static string GlobalPath {get; set;}
}
public class ConfigA : BaseConfig
{
public string pathA {get; set;}
}
public class ConfigB : ConfigA
{
public string pathB {get; set;}
}
class Test
{
static void Main()
{
BaseConfig.GlobalPath = @"c:\users\vulpes";
// check that it's inherited by ConfigA
Console.WriteLine(ConfigA.GlobalPath);
// now change it
ConfigA.GlobalPath = @"c:\users\peter";
// and access it via ConfigB
Console.WriteLine(ConfigB.GlobalPath);
// check that the new value is also available via BaseConfig
Console.WriteLine(BaseConfig.GlobalPath);
Console.ReadKey();
}
}
As expected, the output should be:
c:\users\vulpes
c:\users\peter
c:\users\peter
PeterPosted Feb 1, 2013, 4:18 AM
Maybe you have other solution/sugesstion to my problem.
VulpesPosted Jan 31, 2013, 9:45 AM
This is because the the derived class's constructor will always implicitly or explicitly call the singleton's constructor (which will therefore need to be protected rather than private) effectively creating a new instance of the singleton which would defeat the purpose of having a singleton in the first place.
VulpesPosted Jan 31, 2013, 5:33 AM
So, I don't see how you can achieve what you want by making GlobalConfig into a static class.
If you don't want the GlobalConfig class itself to be capable of instantiation, then you could make it (and the GlobalPath property) abstract. You could then override GlobalPath to provide an actual implementation in ConfigA and inherit that in ConfigB.