Reputation: 989
I saw somewhere (cannot find it anymore) that you can check the existence of an enum value from an enum item with a specific list of items. Ex. below - "Available = doc | xls | csv"
But the following code does not seem to work. I'm expecting the results to be = xls instead of doc, since it is in the list of "Available" values.
Can someone please help?
Thanks in advance!
Niki
Button Code:
protected void btnTest01_Click(object sender, EventArgs e)
{
TestEnum01 result1 = TestEnum01.xls;
TestEnum02 result2 = TestEnum02.xls;
TestEnum03 result3 = TestEnum03.xls;
if (result1 != TestEnum01.Available)
{
result1 = TestEnum01.doc;
}
if (result2 != TestEnum02.Available)
{
result2 = TestEnum02.doc;
}
if (result3 != TestEnum03.Available)
{
result3 = TestEnum03.doc;
}
this.txtTest01_Results.Text =
String.Format("01: Result = {0}, Available = {1}\r\n\r\n02: Result = {2}, Available = {3}\r\n\r\n03: Result = {4}, Available = {5}",
result1.ToString(), TestEnum01.Available,
result2.ToString(), TestEnum02.Available,
result3.ToString(), TestEnum03.Available);
}
ENUMS
public enum TestEnum01
{
doc = 1,
txt = 2,
xls = 4,
csv = 8,
unknown = 5,
Available = doc | xls | csv
}
public enum TestEnum02
{
doc,
txt,
xls,
csv,
unknown,
Available = doc | xls | csv
}
public enum TestEnum03
{
doc,
txt,
xls,
csv,
unknown,
Available = TestEnum03.doc | TestEnum03.xls | TestEnum03.csv
}
RESULTS:
01: Result = doc, Available = Available
02: Result = doc, Available = csv
03: Result = doc, Available = csv
Upvotes: 0
Views: 148
Reputation: 7320
You have to use the FlagsAttribute :
[Flags]
public enum TestEnum01
{
doc = 1,
txt = 2,
xls = 4,
csv = 8,
unknown = 5,
Available = doc | xls | csv
}
Then to test it :
TestEnum01 test = TestEnum01.doc | TestEnum01.txt;
bool isDoc = (test & TestEnum01.doc) == TestEnum01.doc;
Note that in your example, you will have a problem with unknown
value, since binary wise, 1 | 4 = 5 ... And that means doc and xls produces unknown... To avoid this kind of problems, I prefer to use a direct bit-shift notation :
[Flags]
public enum TestEnum01
{
unknown = 0,
doc = 1 << 0,
txt = 1 << 1,
xls = 1 << 2,
csv = 1 << 3,
Available = doc | xls | csv
}
If you just want to test for a particular flag, you can just use the HasFlag()
method
TestEnum01 test = TestEnum01.doc | TestEnum01.txt;
bool isDoc = test.HasFlag(TestEnum01.doc);
Upvotes: 3