Question

I am trying to pass an optional System.DateTime parameter to a constructor in VB.NET 2010.

...
Public Sub New(Optional ByVal givendate As System.DateTime = System.DateTime.MinValue)
    ...

I am getting an error "Konstanter Ausdruck erforderlich" translating to "constant value required". I tried to fill a variable with the MinValue, but I have to make this variable readonly, which leads to exactly the same problem when trying to pass as default value to the optional parameter. Is there a way to pass the MinValue as default value to the optional DateTime (which is actually a Date type). Thank you for your audience.

Was it helpful?

Solution

Well I found a solution in the meantime (thanks to the folks at vbdotnetformums.com, so I would like to share the results:

First possible solution could be defining the parameter as Object and default value as Nothing. Then Cast the DateTime.

Second and cleaner solution (and the one I followed) was to overload the constructor.

Here is the solution by IanRyder (vbdotnetforums.com):

Public Class MyClassExample
  Public Property DateToUseInClass As DateTime

  Public Sub New()
    DateToUseInClass = System.DateTime.Now
  End Sub

  Public Sub New(ByVal GivenDate As System.DateTime)
    DateToUseInClass = GivenDate
  End Sub
End Class

Then I can realise the behavior I wanted to have:

Dim myVariable As New MyClassExample

Dim myVariable As New MyClassExample(DateTime.Today.AddDays(-1))

It worked exactly the way I wanted it. I hope someone else will profit from it some day.

OTHER TIPS

You can set Nothing to default value of function's parameter and then set today's datetime in function

Public Sub New(Optional ByVal fDate As System.DateTime = Nothing)
        If fDate = Nothing Then
            fDate = Now
        End If
    End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top