How can I create a nullable numeric optional parameter in VB.NET?
views:
319answers:
2
+2
A:
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
Ahmad Mageed
2010-01-18 13:44:02
Perfect answer.. thanks a lot..
Rajesh Rolen- DotNet Developer
2010-01-19 04:09:51
+1
A:
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
Mark Brackett
2010-01-18 13:47:50