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?
Asked
Active
Viewed 3,081 times
5

oscilatingcretin
- 10,457
- 39
- 119
- 206
2 Answers
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
-
Good answer, but it makes me sad. – oscilatingcretin Aug 03 '12 at 18:14
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
-
I don't think it's easily possible to avoid literal `Nothing` as a method parameter (which is the case that the OP is talking about). – Heinzi Aug 01 '12 at 11:51
-
That's possible too, optional parameters have always been well supported. – Hans Passant Aug 01 '12 at 11:52