Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a Nullable Optional Numeric (integer/double) parameter in VB.NET?

How can I create a nullable numeric optional parameter in VB.NET?

like image 772
Dr. Rajesh Rolen Avatar asked Nov 28 '22 11:11

Dr. Rajesh Rolen


2 Answers

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
like image 132
Ahmad Mageed Avatar answered Dec 10 '22 04:12

Ahmad Mageed


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
like image 43
Mark Brackett Avatar answered Dec 10 '22 04:12

Mark Brackett