enums

C

Charlie

Below is code for testing whether an enum is part of
a "set" of enums. There must be some better way to do
this. How does one get a group of enums and test for
inclusion? I want to use sets. But maybe collections?
What is the right way to proceed?


enum Suit: int {spade=1, club=2, heart=4,
diamong=8};

private void button1_Click(object sender,
System.EventArgs e)
{
Suit blackSuits = Suit.spade |
Suit.club;
if ((blackSuits & Suit.club) != 0)
MessageBox.Show
(this, "Yes");
else
MessageBox.Show
(this, "No");
}
 
C

Charlie Calvert

Didn't know it would format like that. Here is the example in readable form:

enum Suit: int {spade=1, club=2, heart=4, diamong=8};

private void button1_Click(object sender, System.EventArgs e)
{
Suit blackSuits = Suit.spade | Suit.club;
if ((blackSuits & Suit.club) != 0)
MessageBox.Show(this, "Yes");
else
MessageBox.Show(this, "No");
}

How is one supposed to do this sort of thing? Having to declare the enum
with values such as 1, 2, 4 and 8 is a terrible hack. How am I supposed
to work with enums in C#?

- Charlie
 
R

Richard A. Lowe

Well, I disagree that it's a 'hack' to declare enum values
so that they are bitwise comparable, but that's your
choice to make. This is why the FlagAttribute exists - to
indicate to consumers that an enum is intended for flag or
bitwise comparison.

It's fast and while not intuitively human-readable,
bitwise comparisons are well known constructs, so that
shouldn't be a problem.

Richard
 
C

Charlie Calvert

My apologies for my choice of words. I should be less outspoken. All I
really care about is doing things the "proper way" as defined by common
C# usage, and if this is the way to go, then that is fine with me. I get
used to doing things one way in one language, and I should know enough
to keep an open mind when seeing how things are done elsewhere.
Certainly after working in Java for a bit, I should be grateful that C#
has enums!

- Charlie
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top