Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
1  
Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. Also see How to Ask –  gnat Jun 27 '13 at 11:52

1 Answer 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.

share|improve this answer
    
If you've got something really complicated, enumerations of this sort are probably the wrong way to model it in the first place. –  Donal Fellows Jun 27 '13 at 15:25
    
Yup, this is the canonical example. It's an abuse of enums to do this, but it is the way every system does it. –  Ross Patterson Jun 27 '13 at 23:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.