I just fixed a bug that caught me by surprise. I know enums are just integers internally, but I always assumed that if you try to compare enums of different types, you would get a build error. You don't.
Start a new Visual Studio VB console application and call it WrongEnum. I used .Net Core 6.0. Make Program.vb look like this.
Public Enum Enum1
Success
Fail
End Enum
Fail
Success
End Enum
Console.WriteLine("Success!")
Console.WriteLine("Fail")
Console.Read()
End Module
Run the program and it displays "Fail", even though e was initialized as Success.
Update:
You can also pass the wrong type of enum to a method although this causes a build error if you have Option Strict On.
Consider the method below. You can call it with Enum1 or even an integer when Option Strict is Off. ie PrintSuccess(Enum1.Success). It writes "Fail" to the console.
If you call the method with an integer that is in range it writes the enum's name but if you call it with an integer that is out of range it writes the integer.
No comments:
Post a Comment