using System.Text.RegularExpressions;
using System.Globalization;
public static void Main()
Console.WriteLine(new Regex("^(?:[0-9a-fA-F]{3,4}){1,2}$").IsMatch("8DB3E2"));
SeriesColor str = new SeriesColor("#8DB3E2");
Console.WriteLine(str.R);
Console.WriteLine(str.G);
Console.WriteLine(str.B);
Console.WriteLine(str.A);
Console.WriteLine(str.Hex);
internal struct SeriesColor
public SeriesColor(byte red, byte green, byte blue)
public SeriesColor(byte red, byte green, byte blue, byte alpha)
public SeriesColor(string hex)
var str = ValidatedHexColor(hex);
return "#" + R.ToString("X2") + G.ToString("X2") + B.ToString("X2") + (A==255?"":A.ToString("X2"));
var str = ValidatedHexColor(value);
private static string ValidatedHexColor(string value)
var str = value.TrimStart('#');
if (!new Regex("^(?:[0-9a-fA-F]{3,4}){1,2}$").IsMatch(str)) throw new ArgumentException(value + " is not a valid hex color");
if (str.Length == 3) str = new string(str[0], 2) + new string(str[1], 2) + new string(str[2], 2);
if (str.Length == 4) str = new string(str[0], 2) + new string(str[1], 2) + new string(str[2], 2) + new string(str[3], 2);
private static byte RfromHex(string hex)
return byte.Parse(hex.Substring(0, 2), NumberStyles.HexNumber);
private static byte GfromHex(string hex)
return byte.Parse(hex.Substring(2, 2), NumberStyles.HexNumber);
private static byte BfromHex(string hex)
return byte.Parse(hex.Substring(4, 2), NumberStyles.HexNumber);
private static byte AfromHex(string hex)
return hex.Length != 8 ? (byte)255 : byte.Parse(hex.Substring(6, 2), NumberStyles.HexNumber);