Tuesday, October 30, 2012

Enumeration Format Strings

When you have enum values, there are various shortcuts to pretty-print their values.
The trick is to add the letter required within the ToString() method.

G displays the enumeration entry as a string value, else displays the integer value.
F displays the enumeration entry, else shows each valid entry.
D displays enumeration entry as a integer.
X displays the enumeration entry as a hexadecimal.


Console.WriteLine(ConsoleColor.Red.ToString("G"));         // Displays Red
FileAttributes attributes = FileAttributes.Hidden |
                            FileAttributes.Archive;
Console.WriteLine(attributes.ToString("G"));   // Displays Hidden, Archive   

Console.WriteLine(ConsoleColor.Blue.ToString("F"));       // Displays Blue
FileAttributes attributes = FileAttributes.Hidden | 
                            FileAttributes.Archive;
Console.WriteLine(attributes.ToString("F"));   // Displays Hidden, Archive        

Console.WriteLine(ConsoleColor.Cyan.ToString("D"));         // Displays 11
FileAttributes attributes = FileAttributes.Hidden |
                            FileAttributes.Archive;
Console.WriteLine(attributes.ToString("D"));                // Displays 34         

Console.WriteLine(ConsoleColor.Cyan.ToString("X"));   // Displays 0000000B
FileAttributes attributes = FileAttributes.Hidden |
                            FileAttributes.Archive;
Console.WriteLine(attributes.ToString("X"));          // Displays 00000022         

This was taken from http://msdn.microsoft.com/en-us/library/c3s1ez6e.aspx

  

No comments: