Since a method has to be executed to get this color, you cannot declare the color as constant. A static readonly
field is what comes closest to a const
.
private static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);
private int GetOleFromHTML(string stringRep)
{
Color c;
if (string.IsNullOrWhiteSpace(stringRep))
{
c = DefaultColor
}
else
{
try
{
c = ColorTranslator.FromHtml(stringRep);
}
catch
{
c = DefaultColor
}
}
return ColorTranslator.ToOle(c);
}
Another approach would be to directly store the OLE color as int
.
const int DefaultOleColor = 14737632; // R=224, G=224, B=224
private int GetOleFromHTML(string stringRep)
{
if (string.IsNullOrWhiteSpace(stringRep))
{
return DefaultOleColor;
}
try
{
return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));
}
catch
{
return DefaultOleColor;
}
}
Or calculated explicitly:
const int DefaultOleColor = 256 * (256 * 224 + 224) + 224;
Or with bit shift operations
const int DefaultOleColor = 224 << 16 | 224 << 8 | 224; // My preferred variant.
These expressions can be used to initialize the constant as they can be fully evaluated at compile time.
You can test these variants easily in the Immediate Window of Visual Studio. You must qualify the names with the namespaces for the first variant (System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(224, 224, 224))
).
Avoiding repetition is not the only reason for having constants. Constant declarations give a name to otherwise "magic" values. See Magic number (programming) (Wikipedia).
This variant avoids the repetition by restructuring the code, but still uses a constant.
const int DefaultOleColor = 224 << 16 | 224 << 8 | 224;
private int GetOleFromHTML(string stringRep)
{
if (!String.IsNullOrWhiteSpace(stringRep))
{
try
{
return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));
}
catch
{
}
}
return DefaultOleColor;
}