The standard way is to use an enumeration with the values explicitly set so the binary representations of 0 - 8 are as follows.
0 0000
1 0001
2 0010
4 0100
8 1000
as you can see eac one sets a different bit so you can always tell which ones were selected
so declare an enum:
enum Commitment
{
Heart = 1,
Mind = 2,
Soul = 4
}
Then you can write
Commitment c = Commitment.Heart | Commitment.Soul;
Now its good practice (though not required) to decorate the enum with the
[System.Flags]
attribute. This does two things: it signals to users of the enum that it is intended to me used as a set of bitfields; it changes the way ToStriing works so it prints out a comma separated list of the combined symbols. By default enums occupy 32 bits of storage (so you can have 32 bitwise or-able values). However, you can change this storage type as follows
enum Commitment : byte // any integral type will do fine here
{
...
}
Even though it looks like derivation from a value type (which isn't supported in .NET) it simply states the underlying storage for the enum type.
Regards
Richard Blewett - DevelopMentor
http://staff.develop.com/richardrb/weblog
nntp://news.microsoft.com/microsoft.public.dotnet.languages.csharp/<#u*************@TK2MSFTNGP10.phx.gbl>
Hi,
I've got a class with an Options property. I'd like to implement this
property in a way that a calling syntax like
MyClassInstance.Options = MyClass.Option1 | MyClass.Option2;
can be used. My questions with that:
1. How do I store these BitFlags internally?
2. How do I check for whether certain Bits have been set.
3. The above code shows how to switch 2 bits ON (hopefully, correct me
if I'm wrong). How would the syntax look If I'd like to switch Option1
ON and Option2 OFF?
I'd highly appreceate a short example!
Thanks in advance.
Matthias
[microsoft.public.dotnet.languages.csharp]