How could the typesafe enum pattern be implemented on a generic class? Let’s assume it’s implemented along these lines
public class KnownSetting<T>
{
public readonly static KnownSetting<String> Name = new KnownSetting<String>("name", "Default Name", t => t);
public readonly static KnownSetting<int> Size = new KnownSetting<String>("size", "25", t => Converter.ToInt32);
public String Key { get; set; }
public T DefaultValue { get; set; }
public Func<String, T> Converter { get; set; }
private KnownSetting(String key, T defaultValue, Func<String, T> converter)
{
Key = key;
DefaultValue = defaultValue;
Converter = converter;
}
}
The implementation of the pattern is correct this way since the constructor remains private, but when using this construct, it looks wrong:
public static class Program
{
public static void main()
{
var x = KnownSetting<?>.Name;
}
}
Then an option would be to split it in two, KnownSetting container class and the Setting implementation, but then the scope of the constructor cannot be private so as to be instantiated from within the container.
How can this pattern be implemented so that the generics aspect of it stays concealed from the end-user, but remains strongly typed? Is there a more suitable pattern, or is there a better way to implement it?
Update
I added a second sample to illustrate that I do want the type of the setting to be generic.
Create a helper method in the base type that uses another type and create a known settings class. You need the Create method because the base constructor is Setting(string, object, Func). This is also why I introduce another generic variable (U):