using System.Collections.Concurrent;
public abstract class SmartColor<TColor> where TColor : SmartColor<TColor> {
private static readonly ConcurrentDictionary<string, TColor> _items = new();
protected SmartColor(string code, string name) {
foreach (var field in typeof(TColor).GetFields(BindingFlags.Public | BindingFlags.Static)) {
TColor? item = (TColor?)field.GetValue(null);
public string Code { get; }
public string Name { get; }
public static TColor FromCode(string code) {
if (_items.TryGetValue(code, out var result)) {
private void Register(TColor item) {
_items.GetOrAdd(item.Code, item);
public class WebColor : SmartColor<WebColor> {
public static readonly WebColor White = new WebColor("#ffffff", nameof(White));
public static readonly WebColor Black = new WebColor("#000000", nameof(Black));
protected WebColor(string code, string name) : base(code, name) {
public static void Main()
WebColor color = WebColor.FromCode("#ffffff");
Console.WriteLine(color.Name);