6

How to assign the default Date Time ( Now ) value for optional parameter.

When assigning the now object to optional parameter below error is raised

Constant expression is required

Code:

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

// Code Block

End Sub 
2
  • 2
    What part of the error are you not understanding? Optional parameters have to be constant values. Last time I checked, Now changes fairly often. Apr 16, 2014 at 10:49
  • @Damien_The_Unbeliever, Initially i can't understand the error, Now got it well -- "Optional parameters have to be constant values"
    – bgs
    Apr 16, 2014 at 10:59

2 Answers 2

19

Try this :

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

If ReminderMailDate = Nothing Then ReminderMailDate = Now

// Code Block

End Sub 
1
  • @MattWilko - it's not that different from setting it to default(DateTime) in c#. Apr 16, 2014 at 11:56
13

Instead of using an optional parameter, you might want to consider offering two overloads of your Sub:

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

Public Sub ReminderMail(ByVal ReminderMailDate As DateTime)

// Code Block

End Sub 

Which from a caller's perspective, operates quite similarly.

1
  • 1
    +1. Yes, million times, for maintainability concerns. I was going to post this as an answer myself immediately after I read the accepted answer. Apr 16, 2014 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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