Emiko Takagawi
Emiko Takagawi

Reputation: 11

Verifying enum value is valid in VB.NET

My English may not be very good, so please excuse me if I don't make sense.

I am tasked with verifying an Enum contains a incrementing value.

The code looks like this:

Public Enum AccountMessageDescriptor
  AccountInvalid = 1001
  AccountReviewPending=1002
  ...
  InvalidOperationOnAccount=1382
End Enum

Each Enum value has a description (Custom) attribute also. The file and description attribute is used elsewhere... It looks like the programmers update the enums and use the custom attribute for help messages instead of resource files etc with a new integer value...

For example, another error may be added as:

NewEnumItem=1383

I need to make sure (during build time we have a custom MSBuild task that does lots of other processing) if the enum is incrementing sequentially and that its not already in use.

Someone suggested using a collection, check if the enum value already exists and if not insert it.

I was thinking of just iterating through and checking if the current value is +1 the previous value (so its sequential and it can't be already in use because it has to always be +1). Does this seem flawed or am I not understanding something about .NET enums?

Emmi

Upvotes: 1

Views: 1889

Answers (2)

Koen
Koen

Reputation: 2571

To iterate through an enum, you could try the following:

For Each amd As AccountMessageDescriptor In [Enum].GetValues(GetType(AccountMessageDescriptor))
        'Do your thing here
Next

I'm not enterily sure if this way the values are sequential, but a quick test could sort this out for you.

Or you can store all the values in an array and check if the values are sequential:

Dim allAMD As AccountMessageDescriptor() = DirectCast([Enum].GetValues(GetType(AccountMessageDescriptor)), AccountMessageDescriptor())

'Loop through array and check with previous

Upvotes: 0

El Ronnoco
El Ronnoco

Reputation: 11922

If you set the first value and then exclude all following values they will be incremental. eg...

Public Enum testenum
    first = 1001
    second
    third
End Enum

So second will be 1002 third will be 1003 etc etc...

If for some reason you do need to skip certain values then you can force the increment to start at a higher value eg..

Public Enum testenum
    first = 1001
    second
    third
    fourth = 2000
    fifth
End Enum

So in this example fourth will be 2000 and fifth will be 2001

Upvotes: 1

Related Questions