vote up 1 vote down
star

How do I set a null value for an optional DateTime parameter in a constructor?

I'm using the following constructor below and I want the optional parameter admissionDate to be a null DateTime. Setting it to Nothing actually gives it a value (something like #12:00:00 #).

Public Sub New(ByVal obj1 as Object, Optional ByVal admissionDate As DateTime = System.Data.SqlTypes.SqlDateTime.Null)
flag
add comment

5 Answers:

vote up 1 vote down
check

I'd suggest using James Curran's solution but use Overloading instead of an optional parameter, as a workaround for the error you mentioned ("Optional parameters cannot have structure types") :

Public Sub New(ByVal obj1 As Object, ByVal admissionDate As Nullable(Of DateTime))
  //Your code here
End Sub

Public Sub New(Byval obj1 As Object)
  Me.New(obj1, Nothing)
End Sub

You can also use DateTime? instead of Nullable(Of DateTime) in the latest version of VB (not sure about the older versions).

link|flag
I basically used this solution with overloading (two constructors). But I used SqlDateTime.Null instead of Nothing. – sunpech Mar 6 at 20:04
add comment
vote up 2 vote down

System.Data.SqlTypes.SqlDateTime is not the same as builtin datetime.

You can use that type or use a nullable datetime.

link|flag
add comment
vote up 4 vote down

You'll need a Nullable DateTime. In C#, that's Nullable<DateTime> or DateTime?. I'm not sure of the VB.NET syntax, but I think it's something like Nullable(Of DateTime)

 Public Sub New(ByVal obj1 as Object, _
        Optional ByVal admissionDate As Nullable(Of DateTime) = Null)
link|flag
I'm getting the error: Optional parameters cannot have structure types – sunpech Mar 6 at 18:53
add comment
vote up 1 vote down

Have you tried DBNull.Value?

link|flag
add comment
vote up 2 vote down

I normally use DateTime.MinValue to represent a null date/time.

link|flag
add comment

Your Answer:

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.