How can I create a nullable numeric optional parameter in VB.NET?
EDIT: this should be possible in VB.NET 10 according to this blog post. If you're using it then you could have:
Public Sub DoSomething(Optional ByVal someInteger As Integer? = Nothing)
Console.WriteLine("Result: {0} - {1}", someInteger.HasValue, someInteger)
End Sub
' use it
DoSomething(Nothing)
DoSomething(20)
For versions other than VB.NET 10:
Your request is not possible. You should either use an optional parameter, or a nullable. This signature is invalid:
Public Sub DoSomething(Optional ByVal someInteger As Nullable(Of Integer) _
= Nothing)
You would get this compile error: "Optional parameters cannot have structure types."
If you're using a nullable then set it to Nothing if you don't want to pass it a value. Choose between these options:
Public Sub DoSomething(ByVal someInteger As Nullable(Of Integer))
Console.WriteLine("Result: {0} - {1}", someInteger.HasValue, someInteger)
End Sub
or
Public Sub DoSomething(Optional ByVal someInteger As Integer = 42)
Console.WriteLine("Result: {0}", someInteger)
End Sub
You can't, so you'll have to make do with an overload instead:
Public Sub Method()
Method(Nothing) ' or Method(45), depending on what you wanted default to be
End Sub
Public Sub Method(value as Nullable(Of Integer))
' Do stuff...
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With