I know that, in theory, you can not (and should not) derive static classes in C# but I have a case in which I think I need it... I wanted to define a number of static constants for class A and, as I quickly discovered, you can't do that so I followed this tutorial: http://msdn.microsoft.com/en-us/library/bb397677.aspx
So, I have a static class like this:
public static class ClassAConstants
{
public const string ConstantA = "constant_a";
public const string ConstantB = "constant_b";
}
Then, I have class B that extends class A and adds some new static constants. What I would like to do is this:
public static class ClassBConstants : ClassAConstants
{
public const string ConstantC = "constant_c";
public const string ConstantD = "constant_d";
}
This way, the four constants would be accessible with ClassBConstants.ConstantA or ClassBConstants.ConstantD. However, C# won't let me do it.
How can I achieve this? Perhaps the solution is totally different, I don't care if it does not use static constants at all as long as the result is what I want.
EDIT:
Thanks to Amby I discovered that constants are implicitly static so I really didn't need to create that artificial static classes (ClassAConstants and ClassBConstants). The solution couldn't be simpler:
public class A
{
public const string ConstantA = "constant_a";
public const string ConstantB = "constant_b";
// ...
}
public class B : A
{
public const string ConstantC = "constant_c";
public const string ConstantD= "constant_d";
// ...
}
With that code I get the results I wanted initially.
Choose Singleton instead of static class.
Then your class benefits from features available to a non-static class, and the user will just have to make the following changes:
ClassAConstants.ConstantA ... to ... ClassAConstants.Instance.ConstantA
By the way, if you are only interested in consts, then the below code would also compile. And then you can access these constants from instance of these classes, or directly by using class name (like accessing static member).
public class ClassAConstants
{
public const string ConstantA = "constant_a";
public const string ConstantB = "constant_b";
}
public class ClassBConstants : ClassAConstants
{
public const string ConstantC = "constant_c";
public const string ConstantD = "constant_d";
}
This is possible since consts are implicitly static.
ClassAConstants.ConstantA .. works.
ClassBConstants.ConstantA .. works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With