Home » c# » Assign Multiple enum Values To One Variable

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:

image

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 = 4
End 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 = 4
End Enum

fvar will evaluate to:

thing1 | thing2

in CSharp and in VB.NET…

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

 

Other post in c#

Related Post

  • The VB.NET Ternary OperatorThe VB.NET Ternary Operator I think the VB.NET Ternary Operator may be the last operator that I really miss in VB.NET from my curly brace language experience.  Although, I have to admit, I wouldn't have missed it all […]
  • Object Initialization in CSharp 3.0 and VB.NET 9Object Initialization in CSharp 3.0 and VB.NET 9 Yesterday we looked at the new var keyword in CSharp.  This makes CSharp variable declaration similar to VB.  After all, they've had the DIM keyword for years which essentially does the […]
  • Simple Properties in C# 3.5Simple Properties in C# 3.5 It's such a little thing.  But, how much of our CSharp code looks something like this: private string _propertyName; public string PropertyName { get { […]
  • CSharp adds the var keyword!CSharp adds the var keyword! There have been several new features added to the CSharp language that will significantly reduce the amount of code that ends up in our source files.  It will not significantly reduce the […]
  • Why you can’t cast an integer to a string.Why you can’t cast an integer to a string. I saw a question on Channel 9 that I've heard before. My guess is that there are enough people who have the same question that it's worth addressing. I know there's probably a really good […]

About Dave Bush

Dave Bush is a Full Stack ASP.NET developer focusing on ASP.NET, C#, Node.js, JavaScript, HTML, CSS, BootStrap, and Angular.JS. Does your team need additional help in any of the above? Contact Dave today.