[Flags] on Enums Make ToString() Smart

Putting the [Flags] attribute on an enum changes ToStrings behaviour. It generates a comma separated list.

I’ve used enums a lot. I’ve occasionally used the [Flags] attribute too. But I’ve never paid attention to how ToString() changes behaviour when the [Flags] attribute is added. Not until a couple of days ago, when I learnt something new (to me at least) and useful. The [Flags] attribute will make ToString() return a comma separated list of the flags set.

Let’s look take a small enum with screen colors as an example.

[Flags]
enum Colors
{
  Black = 0,
  Red = 1,
  Green = 2,
  Blue = 4,
  Yellow = Red | Green
}

Colours are created as combinations of red, green and blue:

var violet = Colors.Red | Colors.Blue;
var white = Colors.Red | Colors.Green | Colors.Blue;
var myYellow = Colors.Red | Colors.Green;
var myRed = Colors.Black | Colors.Red;

The value of white is 5 and the value of yellow is 3. Without the [Flags] attribute, ToString() would return the numerical value, because there is no Colors value mapped to 3 or 5. With the [Flags] attribute applied, ToString() returns a comma separated list instead:

violet.ToString(): Red, Blue
myYellow.ToString(): Yellow
white.ToString(): Yellow, Blue
myRed.ToString(): Red
Colors.Black.ToString(): Black

It tries it best to make an as short a list as possible. When the red and green flags are set, they are combined into yellow. The zero option (black) is only displayed if the value is indeed zero.

This is nothing complex, neither anything that’s new (even though I’ve somehow missed it). I’m just happy I learnt something new that might be useful.

Software Development is a Job – Coding is a Passion

I'm Anders Abel, a systems architect and developer working for Kentor in Stockholm, Sweden.

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

The complete code for all posts is available on GitHub.

Popular Posts

Archives

Series

Powered by WordPress with the Passion for Coding theme.