I need a way to create a static class where some constants can be specific, but hardcoded.
What I really want to do is a class in which several extended constants are provided when the class is extended - I want the "constants" to be hard-coded. I decided that I would make some abstract properties and define get {return constant; } when extending a class.
I know this is not possible, so now I have two options, and I wonder what would be better and why (if there are options that I miss, let me know!)
- Create a static class with fields with a null value and throw an exception if the fields have a null value when the static method is called.
- Discard the static class. Have a non-static class with abstract properties and instantiate the object wherever I need it, although all the functionality is really static.
I know that this can be subjective and case-dependent, however I go around in circles thinking about it and really can do it with some external input. This is a plus, I hope that there can be something to do what I want, and I just think about it wrong.
Update:. Code: I will try to write code that describes what I would like to accomplish. I know this code cannot work!
Imagine that the abstract Calculation class is in a dll that is used by many projects. The functionality is the same for all of them, just the constant varies from project to project.
public abstract static class Calculation { private abstract int Constant { get; }
The Calc class is defined in a separate project where functionality is required and a constant is known.
public static class Calc : Calculation { private override int Constant { get { return 2; } } ... static class Program { [STAThread] static void Main() {
I suppose the easiest way would be to create a non-static class and instantiate, however, I fear that multiple instances of the class might be expensive and would like to prevent this if possible.
I donβt see how I could write this as a singleton template without writing it again in every project - having only the Nested class in the dll. This will not prevent the developer from simply creating a regular class and will probably restart the discussion for each project that uses code.
Update # 2 . What can I say with option 1:
Class in dll:
public static class Calculation { public int? Constant {get; set;} public static int Calculate(int inputValue) { if (Constant == null) throw new ArgumentNullException(); return inputValue * (int)Constant; } }
Using the function in a separate project:
static class Program { [STAThread] static void Main() {
Option one is very simple and elegant, which worries me that nothing forces the creator to set a constant. I fear (admittedly, unlikely) a scenario where an obscure edge case will cause the property to not be set and the code to fail (and the constant to be the last suspect) ...