I just have read some stuff on enum today. Use of flags with enum was something interesting and new for me. But often practice and theoretical uses are different. I go through many articles they examples they quoted were good to get the concept but am still wondering in what situations one can use Enums with flag to store multiple values?
Will highly appreciate if you please can share your practical experience of using enum with flags.
1
In C#, the example that sticks out in my head is accessing a directory of files. System.IO.FileAttributes is a flag enumeration of every attribute that a file can have. It makes more sense to contain all of this information in one place then have a bunch of properties that have to be set.
File.SetAttributes(file, FileAttributes.ReadOnly | FileAttributes.System);
This is much more concise than code that would have you individually set each boolean field on on the file’s attributes. Since every flag value is valid in any combination (except Normal, which is valid only by itself), combining them works. Now if files could only ever be of two different values with complex rules governing which combinations worked, then I would make FileAttributes a structure that could do the logic necessary to sort out those requirements.
2
It has been a long time since the question was asked and this may help somebody looking for an answer in the future.
Let’s say you give your user the ability to show or hide columns in a grid and you want to persist those settings without lots of individual settings being persisted.
Saving a value of 3 to persisant storage allows you to retrieve a single value from that storage but be able to set multiple values from that single number.
An example being
var columnsVisibity = (SearchResultsColumnOptions)3; //this number has been retieved from persistant storage
SearchResultsGrid.Columns[0].Visible = columnsVisibity.HasFlag(SearchResultsColumnOptions.Artist);
SearchResultsGrid.Columns[1].Visible = columnsVisibity.HasFlag(SearchResultsColumnOptions.Title);
SearchResultsGrid.Columns[2].Visible = columnsVisibity.HasFlag(SearchResultsColumnOptions.Disc);
[Flags]
public enum SearchResultsColumnOptions:byte
{
None = 0b000,
Artist = 0b001,
Title = 0b010,
Disc = 0b100,
All = 0b111
}
The result of this example would be that the disc column would not be visible.
I hope this helps somebody as have tried to make this a simple example as possible.