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

How to create a null numeric optional parameter in VB.NET ?

+4
source share
4 answers

EDIT: this should be possible in VB.NET 10 as per this blog post . If you use it, you can:

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 must either use an optional parameter or a NULL value. This signature is not valid:

 Public Sub DoSomething(Optional ByVal someInteger As Nullable(Of Integer) _ = Nothing) 

You will get this compilation error: "Optional parameters cannot have structure types."

If you use nullable, set to Nothing if you do not want to pass a value to it. 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 
+13
source

You cannot, so you have to redo the overload:

 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 
+5
source

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

+1
source

I understand this in VS2012 version, for example

 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 
0
source

All Articles