Question optional Date

Zexor

Well-known member
Joined
Nov 28, 2008
Messages
520
Programming Experience
3-5
I am trying to have an optional Date value in one of my sub but since you cant set Date to nothing, this doesn't work. And i cant set it to the Date.minvalue inline.
VB.NET:
Private Sub abc (ByVal A As String, Optional ByVal B As Date = Nothing)
End Sub

so, i went and set it to some date in the past.
VB.NET:
Private Sub abc (ByVal A As String, Optional ByVal B As Date = #1/1/2001#)
End Sub

what would be the proper way to handle the default value for an optional Date?
 
A Date can't have no value, just like all value types. How would you have an optional Integer? All you could do is use 0, but that's still a value. If you want to use value type and genuinely make them nullable then that's what you have to use: nullable value types:
VB.NET:
Private Sub abc (ByVal A As String, Optional ByVal B As Nullable(Of Date) = Nothing)
or, in shorthand:
VB.NET:
Private Sub abc (ByVal A As String, Optional ByVal B As Date? = Nothing)
Note now that your parameter is no longer a Date, but a Date?, so you have to treat it as such. That means that you have to test that it has a value before you use it.
 
Error

When i try those, it give me this error.

Optional Parameters cannot have structure types.
 
In that case just don't use an optional parameter. I pretty much never do anyway.
VB.NET:
Private Overloads Sub abc(ByVal A As String)
    Me.abc(A, Nothing)
End Sub

Private Overloads Sub abc(ByVal A As String, ByVal B As Date?)
    'Do something here.
End Sub
One advantage of that, which may never come into play, is that the second parameter will be optional for anyone calling your method from C# too.
 
Back
Top