-1

When working with optional arguments, I like to default them to Nothing.

Sub DoSomething(ByVal Foo as String, Optional ByVal Bar as String = Nothing)
    If Bar IsNot Nothing then DoSomethingElse(Bar)
    DoAnotherThing(Foo)
End Sub

This works great, unless you start working with Enum types (or an Integer and other Data types). In which case my Enum list includes a 'None' value, as follows:

Enum MyEnum
    None
    ChoiceA
    ChoiceB
End Enum
Sub DoSomething(ByVal Foo as String, Optional ByVal Bar as MyEnum= MyEnum.None)
    If Bar = MyEnum.None then DoSomethingElse(Bar)
    DoAnotherThing(Foo)
End Sub

It works, but I am looking for alternatives. In addition to the burden of creating a 'None' entry in a custom Enum, this is just not possible to do with enumerations defined by the framework or a third party DLL.

Ama
  • 1,373
  • 10
  • 24
  • A nullable parameter would be an alternative, `As MyEnum? = Nothing`. – Hans Passant Apr 17 '19 at 12:23
  • `ByVal Foo as String, Optional ByVal Bar As MyEnum? = Nothing` would work, because the underlying type that is used to declare an enumeration cannot be nullable. – Trevor Apr 17 '19 at 12:25

2 Answers2

1

As is often the case, I went across a few answers as I was drafting the question.

This post and the .NetDocumentation suggest the use of a nullable:

Sub DoSomething(ByVal Foo as String, Optional ByVal Bar as Nullable(Of MyEnum) = Nothing)
    If Bar IsNot Nothing then DoSomethingElse(Bar)
    DoAnotherThing(Foo)
End Sub

Or,

Sub DoSomething(ByVal Foo as String, Optional ByVal Bar as Nullable(Of MyEnum) = Nothing)
    If Bar IsNot Nothing then DoSomethingElse(Bar)
    DoAnotherThing(Foo)
End Sub

Never used this so any comments / warnings going this way are most welcome!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ama
  • 1,373
  • 10
  • 24
1

In your example, it could make more sense to overload.

Sub DoSomething(ByVal Foo as String, ByVal Bar as MyEnum)
    DoSomethingWithBar(Bar)
    DoSomething(Foo)
End Sub

Sub DoSomething(ByVal Foo as String)
    ' Do something with Foo
End Sub
the_lotus
  • 12,668
  • 3
  • 36
  • 53
  • I do use overloads extensively in some intances, but there are cases where the benefits of an `Optional` win. Generally speaking I find overloads reduce readability and make code maintenance more prone to errors. Having said that, it has the benefit of providing distinct XML documentation tags. – Ama Apr 17 '19 at 12:17
  • @Ama you also don't have a None, Nullable and If. – the_lotus Apr 17 '19 at 12:20
  • This definitely is an advantage towards None. If `Nullable` was not an alternative, I would go for overloading. – Ama Apr 17 '19 at 12:30