Error code handling with Enumerations

I’m working with an external C library that has a bunch of numerical error codes. The codes have plain english definitions. For example:

#define ERROR_OK				0
#define ERROR_ALREADY_INIT		-100
#define ERROR_NOT_STARTED		-104

Calling a function will return one of these numerical values if something goes wrong. There are about 20 of them in total. I’d like to have an easy way to access the plain English error given the number. I was thinking of using an enumeration to do this but from how I’m reading it, the “key” in an enumeration would be the text, not the error code. I need the opposite, where the key is the code and the value is the text.

I could set up a dictionary I suppose, but I was hoping to just use something like the enumerations editor to set it up once and not have to load that up into a dictionary on startup. Can this be done?

Enumerations, as you say, would work the other way around. It would allow you to use the text to find the value. Which isn’t what you want.

If you want to turn the number into text to show to a user then a dictionary would be a decent option. If there are not a lot of numbers then you could have a case statement that would check the values and return the appropriate string.


Thanks. That’s what I thought. I was hoping I could just set up the enumerations once and have it all self-contained, instead of having to write the code to populate the dictionary every time I launch. Not that it’s expensive, I just thought it would be nicer that way. Oh well.

Yup, enums don’t work backwards. If you look at the documentation is suggests a method of returning the names, however, it is just a switch statement using the enum.

What i want is the opposite though - the library returns the error number and I want to translate that into the human-readable text to display in the UI.

I just implemented it with a dictionary and it seems to work fine.

I understand.
I usually make the enumeration this way, then I make a “tostring” method, with the enum as a parameter, and that returns the error as a detailled string.
it must be the same with a dictionnary

it’s really easy and fast to make chatgpt do all the boring code for you…

You can cast enumerations to an integer, fyi.


And then…

Var someInteger as Integer = -344

select case someInteger
case Integer(myEnums.First)
case Integer(myEnums.Second)
case Integer(myEnums.third)
End Select

And you get…

Cast less:

   Var enumvalue as myEnums = ctype( -344, myEnums )

   select case enumvalue
   case myEnums.First
   case myEnums.Second
   case myEnums.third
   End Select

Catch err As IllegalCastException
   MsgBox("Invalid value")
End Try
1 Like

You can convert int to enum using Ctype.

Var x as MyEnum = Ctype(intValue, MyEnum)


Ian “Ninjaed” you. :slight_smile:

Thanks to you both for the insight; I was unaware you could use CType like this.

I use this for declare work all the time.