Assign Multiple Enum values to one variable.

I saw this question and immediately thought, “You can’t!  An Enum is an Integer that has been restricted to the values it can accept.”

And I was basically right.  But, I forgot that even with an integer you can do the following in CSharp:

int i = 1 | 2;

And in VB.NET

Dim i As Integer = 1 Or 2

To end up with a variable i equal to 3 because both do bitwise ands.

So if I had an enumerated value

enum F { thing1 = 1, thing2 = 2, thing3 = 4 }
Or, in VB.NET
Enum F thing1 = 1 thing2 = 2 thing3 = 4End Enum

You could then do the following in CSharp:

F fvar;

fvar = F.thing1 | F.thing2;

Or you could do it in VB.NET like this:

Dim fvar As F = F.thing1 Or F.thing2

There’s just one small problem with doing all of this.  If you evaluate fvar, you see that it is equal to 3 because we did not define 3 to be a specific value in our enumeration.  However, by adding the Flags attribute to our enum definition:

[Flags]enum F { thing1 = 1, thing2 = 2, thing3 = 4 }

Or

<Flags()> _Enum F thing1 = 1 thing2 = 2 thing3 = 4End Enum

fvar will evaluate to:

thing1 | thing2

in CSharp and in VB.NET…

Well, in VB.NET it still evaluates to 3.

del.icio.us Tags:

Technorati Tags:


Other Related Items:

Bare Escentuals BareMinerals Rocker Eye Tutorials: 2x Eye Color 0.28g + Liner Shadow 0.28g + Double-Ended Rock ' N ' Roll Brush - 4pcsBareMinerals Rocker Eye Tutorials: 2x Eye Color 0.28g ( # 1980s, # Rock Star ) 1x Liner Shadow 0.28g ( # Black Leather ) 1x Double-Ended Rock ' N ' Roll Brush
Cars - Flash Cards - Multiplication Learning Game CardsCars - Flash Cards - Multiplication Learning Game Cards

These flash cards teach children multiplication facts from zero to eleven, and includes cards introducing twelve. Each card has the answer on the opposite side in the bottom right corner.

If you're new here, you may want to subscribe to the mailing list to get notifications of new post and a virtual tour of past topics. Thanks for visiting!

Related Post

Comments are closed.

DotNetNuke Sponsor

 

Most Valuable Blogger
Sponsor