Enum

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I have the following Enum

Public Enum Mode
Required
Validate
End Enum

How can I make a variable of type Mode to hold both Required and
Validate values without needing to add an option to my enum named
RequiredValidate?

And how can I check if that variable contains Required, Validate or
Required and Validate?

Is this possible?

Thanks,

Miguel
 
You can't.

An enum is logically the same as an Integer. So trying to store both
Required and Validate in a variable declared as Mode is like trying to
store a zero and a one in an Integer that will only hold a zero or a
one. (or a one and a two)

You are going to need a third item in the Enum.

-----Original Message-----
From: shapper [mailto:[email protected]]
Posted At: Wednesday, October 31, 2007 7:42 AM
Posted To: microsoft.public.dotnet.framework.aspnet
Conversation: Enum
Subject: Enum

Hello,

I have the following Enum

Public Enum Mode
Required
Validate
End Enum

How can I make a variable of type Mode to hold both Required and
Validate values without needing to add an option to my enum named
RequiredValidate?

And how can I check if that variable contains Required, Validate or
Required and Validate?

Is this possible?

Thanks,

Miguel
 
You need to add the Flags attribute to the enum. You should set each value
specifically to be the value of a single bit (i.e. 1, 2, 4, 8, 16, etc...).
This way you can tell which enum flag is in a value. If you have the value
of 5 that means you have the enum values of 1 and 4.

Your example is below:

<Flags> _
Public Enum Mode
Required = 1
Validate = 2
End Enum
 
MyMode=Mode.Required Or Mode.Validate is perfectly valid

If you want to create a value that combine both you'll have to add this
value to your enum as RequiredValidate=Required Or Validate

Each value is a power of two so that you can combine values into a single
value (using or) or test them (using and).

See
http://msdn2.microsoft.com/en-us/library/system.flagsattribute(VS.80).aspx
for details...

To do this, add a <Flags()> attribute before the enum
 
Back
Top