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,
Volvo
}
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?
You already got an answer to that from Bala R — try
Option Strict On.It’s not the
enums 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
enums probably aren’t the best option. Even C# allows you to (explicitly) cast a value of oneenumtype to a differentenumtype.