.NET Zone is brought to you in partnership with:

I'm a software developer working as a senior consultant at Kentor in Stockholm, Sweden. My core competence is as a technical specialist within development and system architecture. In my heart I am, and probably will remain, a programmer. I still think programming is tremendously fun, more than 20 years after I first tried it. That's why my blog is named Passion for Coding.  Anders is a DZone MVB and is not an employee of DZone and has posted 85 posts at DZone. You can read more from them at their website. View Full User Profile

[Flags] on Enums Make ToString() Smart

  • submit to reddit

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.

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.

Published at DZone with permission of Anders Abel, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)