Look, I know static classes can't inherit or implement. The question is "what the heck is the right C# + OOP pattern to implement this?". "This" is described below:
I want to define a common set of both definition and implementation for a group of classes where all but one type should be static. Namely, I want to make some arbitrary base converters where each have exactly the same four members:
// Theoritical; static classes can't actually implement
interface IBaseConverter {
int Base { get; }
char[] Glyphs { get; }
int ToInt(string value);
string FromInt(int value);
}
// AND / OR (interface may be superfluous)
public class BaseConverter : IBaseConverter{
public BaseConverter(int Base, char[] Glyphs) {
this.Base = Base;
this.Glyphs = Glyphs;
}
public int Base { get; private set; }
public char[] Glyphs { get; private set;}
public int ToInt(string value) { // shared logic...
public string FromInt(int value) { // shared logic...
}
They can also share the exact same implementation logic based on the value of Base
and the ordered collection of glyphs. For example a Base16Converter
would have Base = 16
and glyphs = { '0', '1', ... 'E', 'F' }
. I trust the FromInt
and ToInt
are self-explanatory. Obviously I wouldn't need to implement a converter for base 16, but I do need to implement one for an industry-specific base 36 (the 0
- Z
glyphs of Code 39). As with the built-in conversion and string formatting functions such as [Convert]::ToInt32("123",16)
these are emphatically static methods -- when the base and glyphs are pre-determined.
I want to keep an instance version that can be initialized with arbitrary glyphs and base, such as:
BaseConverter converter = new BaseConverter(7, new[]{ 'P', '!', 'U', '~', 'á', '9', ',' })
int anumber = converter.ToInt("~~!,U") // Equals 8325
But I also want a static class for the Base36Code39Converter
. Another way of putting this is that any static
implementers just have hard-coded base and glyphs:
// Theoritical; static classes can't inherit
public static class Base36Code39Converter : BaseConverter {
private static char[] _glyphs = { '0', '1', ... 'Z' };
static Base36Code39Converter : base(36, _glyphs) { }
}
I can see why this wouldn't work for the compiler -- there is no vtable for static methods and all that. I understand that in C# a static class cannot implement interfaces or inherit from anything (other than object) (see Why Doesn't C# Allow Static Methods to Implement an Interface?, Why can't I inherit static classes?).
So what the heck is the "right" C# + OOP pattern to implement this?