[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.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.