5

It's really bugging me that the VS 2010 IDE isn't barking at me for trying to pass Nothing through a method parameter that takes an user-defined enum. Instead, it's passing 0 through to the method. c# would never allow this. Is there some module-level modifier I can add like option strict that will force the IDE to not allow these types of implicit conversions?

oscilatingcretin
  • 10,457
  • 39
  • 119
  • 206

2 Answers2

8

Sadly, no.


But you can assign values to your enumeration members while skipping 0 (or use a placeholder named None or something like that), and at least handle this case at run time.

Sub Main
    MyMethod(Nothing) ' throws Exception
End Sub

Sub MyMethod(e as MyEnum)
    If e = 0 Then
        Throw New Exception
    End If
End Sub

Enum MyEnum
    a=1
    b=2
    c=3
End Enum
sloth
  • 99,095
  • 21
  • 171
  • 219
3

Nothing is the equivalent of default in the C# language. So no.

Reconsider your programming style, Nothing should be used very sparingly. Basically only in generic code, same place you'd use default in C#. You don't need it anywhere else, VB.NET doesn't insist on variable initialization like C# does. Any variable of a reference type gets initialized to Nothing automatically. Cringe-worthy to a C# programmer perhaps, but entirely idiomatic in VB.NET code.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536