Click here to Skip to main content
15,914,111 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Say
C#
enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }

...

var str1 = (Suits.Spades | Suits.Diamonds).ToString();
           // "5"

Why it is "5"? I don't understand it.
Posted
Comments
Sergey Alexandrovich Kryukov 12-Feb-15 19:25pm    
What would you expect? Do you at least understand why 1 | 4 == 5? Or your confusion is only about the string?
—SA

In addition to Solution 2:

Please see my comment to the question. The attribute System.FlagsAttribute affects only one thing: string representation of enumeration values, and, hence, all cases when such representation is used, such as debuggers. If does not affect any other functionality. Reflection examines your enumeration members' name and generates bit-combined names. If you are curious to know how such things work, you can read my article Enumeration Types do not Enumerate! Working around .NET and Language Limitations[^].

—SA
 
Share this answer
 
Spades = 1 dec = 001 bin
Diamonds = 4 dec = 100 bin

| = bitwise or[^]

hence: 001 bin | 100 bin = 101 bin = 5 dec

Or you can think of it as adding a specific bit to the result. That's why flags[^] should always be defined as powers of 2.
 
Share this answer
 
Comments
Tomas Takac 12-Feb-15 17:30pm    
Why the down vote? I admit I'm not completely sure this is what the OP is asking but it's definitely not wrong.
PIEBALDconsult 12-Feb-15 19:41pm    
I don't see any downvotes.
Numbers in a computer are binary. Or symbol | is doing 001 OR 100 = 101 which is 5 in binary.
 
Share this answer
 
Because you didn't use the FlagsAttribute.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900