VB.NET and Enums

I’ve run into several problems with the way the VB.NET compiler handles enums.

I’ve described one here, a while ago. In a nutshell, an enum exposed by SPS was based on the non-CLSCompliant UInt32 datatype, and VB.NET was choking on it during compilation.

The second one I ran into recently was when using the Enterprise Library to access an Oracle database. I was trying to create a paramater for an OracleCommandWrapper object. The AddParameter method has the following overloads:

AddParameter(String Name, System.Data.DbType type, …)
AddParameter(String Name, System.Data.Oracle.OracleType type, …)

Both overloads accept an enum as the second parameter, and the rest of the arguments are identical. Both enums are based on Int32. When compiling a call to this method, I got a compiler errors saying that no accessible overload was available without a narrowing conversion.

I’m still not entirely sure what this compiler error meant. My suspicion is that since both enums are ultimately the same datatype, it cannot determine which overload to call. I would be glad to know exactly what it means.

The solution for both problems, however, was identical and involved mostly confusing the VB.NET compiler with shiny lights:

Instead of calling AddParameter(“Name”, OracleType.Cursor, …), I called it like this: AddParameter(“Name”, [Enum].Parse(GetType(OracleType), OracleType.Cursor.ToString()), …).

In effect, I print out the enum value as a string and then re-parse it into an enum. This trick seems to convince the compiler that everything is fine, and it compiles (and runs) smoothly. A simple CType() cast does NOT work. This solution also worked for the UInt32 enum in SPS – the compiler complained that it didn’t know what UInt32 was, but once I’ve perpetrated my little deception, everything was cool.

Anyone more familiar with the VB.NET compiler and can explain this behavior?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.