I thought that enums in VB and C# where the same or at least very similar. Then today I stumbled across a bug in our VB code. The following VB code compiles and runs with no issues:
Enum Cars
Subaru
Volvo
End Enum
Enum Vegtables
Carrots
Beets
End Enum
Sub Main()
Foo(Cars.Subaru)
Foo(Vegtables.Carrots)
End Sub
Public Sub Foo(ByVal value As Cars)
End Sub
But the equivalent in C# correctly shows an error:
enum Cars
{
Subaru,
V开发者_运维问答olvo
}
enum Vegtables
{
Carrots,
Beets
}
class Program
{
static void Main(string[] args)
{
Foo(Cars.Subaru);
Foo(Vegtables.Carrots);//<-- C# detects a type mismatch here
}
public static void Foo(Cars carsValue)
{}
}
Why does the VB version not catch the type mismatch? Are enum in VB and C# different?
Why does the VB version not catch the type mismatch?
You already got an answer to that from Bala R — try Option Strict On
.
Are enum in VB and C# different?
It's not the enum
s themselves that are different (your declarations in both C# and VB.NET are as equivalent to one another as they can be and will in all probability result in identical CIL "bytecode"). It's rather that the compilers differ in the type safety they provide at compile-time / the implicit type coercion they allow.
If type safety is very important to you, then enum
s probably aren't the best option. Even C# allows you to (explicitly) cast a value of one enum
type to a different enum
type.
Turn Option Strict
option for VB.NET compilation and it will catch the mismatch.
精彩评论