Reputation: 14285
How can I create a nullable numeric optional parameter in VB.NET?
Upvotes: 4
Views: 15328
Reputation: 5808
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
Upvotes: 0
Reputation: 21
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
Upvotes: 2
Reputation: 96507
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
Upvotes: 16
Reputation: 85665
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
Upvotes: 6