Optional parameter with current value (Date) by default

How to assign a default date value (now) to an optional parameter.

When assigning the now object to an optional parameter below, the error is increased

Constant expression is required

the code:

Public Sub ReminderMail(Optional ByVal ReminderMailDate As DateTime = Now)

// Code Block

End Sub 
+4
source share
2 answers

Try the following:

Public Sub ReminderMail(Optional ByVal ReminderMailDate As DateTime = Nothing)

If ReminderMailDate = Nothing Then ReminderMailDate = Now

// Code Block

End Sub 
+11
source

Instead of using an optional parameter, you may need to consider two of your overloads Sub:

Public Sub ReminderMail()
    ReminderMail(DateTime.Now)
End Sub

Public Sub ReminderMail(ByVal ReminderMailDate As DateTime)

// Code Block

End Sub 

Which from the perspective of the caller works the same way.

+10
source

Source: https://habr.com/ru/post/1536757/


All Articles