Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

You can also use an object:

Public Sub DoSomething(Optional ByVal someInteger As Object = Nothing)
If someInteger IsNot Nothing Then
  ... Convert.ToInt32(someInteger)
End If

End Sub

I figure it out in VS2012 version like

Private _LodgingItemId As Integer?

Public Property LodgingItemId() As Integer?
        Get
            Return _LodgingItemId
        End Get
        Set(ByVal Value As Integer?)
            _LodgingItemId = Value
        End Set
    End Property

Public Sub New(ByVal lodgingItem As LodgingItem, user As String)
        Me._LodgingItem = lodgingItem
        If (lodgingItem.LodgingItemId.HasValue) Then
            LoadLodgingItemStatus(lodgingItem.LodgingItemId)
        Else
            LoadLodgingItemStatus()
        End If
        Me._UpdatedBy = user
    End Sub

Private Sub LoadLodgingItemStatus(Optional ByVal lodgingItemId As Integer? = Nothing)
    ''''statement 
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top