views:

455

answers:

5

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)
+2  A: 

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

Otávio Décio
+1  A: 

Have you tried DBNull.Value?

TheTXI
+4  A: 

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)
James Curran
I'm getting the error: Optional parameters cannot have structure types
sunpech
+2  A: 

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

You can use that type or use a nullable datetime.

Cade Roux
+1  A: 

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).

Meta-Knight
I basically used this solution with overloading (two constructors). But I used SqlDateTime.Null instead of Nothing.
sunpech