Home
Map
Color TableGenerate a table containing HTML colors with names. Access the KnownColors enum.
C#
This page was last reviewed on Sep 24, 2022.
Color table. We can enumerate colors in the C# language. We build a table containing all named colors, making HTML easier to write.
Some notes. With a foreach loop, we can enumerate the values in an enum like the type KnownColor. We can write the color table directly to the console.
Color
enum
Example. We use the Enum.GetNames method and the typeof operator along with the Where extension method. With Where, we remove Control colors from the output.
Enum.GetName
where
Tip In .NET 6 in 2022, the program compiles and runs correctly without adding any assemblies.
However In previous versions of the .NET Framework, adding System.Drawing assembly might be needed.
And It uses the StartsWith method and LINQ extension methods. These help generate the correct output.
String StartsWith
using System; using System.Drawing; using System.Linq; class Program { static void Main() { // Get enum strings and order them by name. // Remove Control colors. foreach (string c in Enum.GetNames(typeof(KnownColor)).Where( item => !item.StartsWith("Control")).OrderBy(item => item)) { // Write table row. Console.WriteLine("<b style=background:{0}>{1}</b>", c.ToLower(), c.ToLower().PadRight(20)); } } }
Discussion. In this example, the KnownColors can be enumerated and listed. The C# code also helps us learn about how to use this programming language.
Summary. We can enumerate KnownColors from the System.Drawing namespace. Next we saw the console program that generates the table. A color sheet can be useful for selecting named colors.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 24, 2022 (edit link).
Home
Changes
© 2007-2024 Sam Allen.