简体   繁体   中英

How can i set system.nullable of datetime as an optional parameter in a subroutine?

I tried the following, but i get the error

constant expression is required

Public Sub ExampleSub(ByVal Test as string, 
  Optional ByVal fromDate As System.Nullable(Of DateTime) = Date.Today)
'A Great sub!
End sub

and here is the C#

public void ExampleSub(string Test, 
  System.Nullable<DateTime> fromDate = System.DateTime.Today)
{
    //A Great sub!
}

Thanks in advance

You can't, the compiler tells you why :)

in C#:

public void ExampleSub(string Test)
{
    //A Great overload!
    ExampleSub(Test, System.DateTime.Now);
}

public void ExampleSub(string Test, System.Nullable<DateTime> fromDate)
{
    //A Great sub!
}

Now, IFF you know that null will not be legitimately by passed in by a caller, you could do:

public void ExampleSub(string Test, System.Nullable<DateTime> fromDate = null)
{
    fromDate = fromDate?? System.DateTime.Now;
    //An Even Greater sub!
}

You can't use a non-constant expression for the default parameter. System.DateTime.Today will depend on when you run the program so it is not constant.

Use a constant expression for default and then check for that and set fromDate to System.DateTime.Now in the routine. Normally null would be used as the special value as in @sehes answer. If null has another special meaning to your code you could use a value which will never be used as the defaul parameter, eg System.DateTime.MinValue :

public void ExampleSub(string Test, 
  System.Nullable<DateTime> fromDate = DateTime.MinValue)
{
    fromDate = fromDate == DateTime.MinValue ? System.DateTime.Now : fromDate;
    //A Great sub!
}

If someone is doing this in VB.Net this is a way I solved my issue, I didn't find the exact thing on this thread, if it helps someone:

  /*I set below line as parameter in method*/
  Optional ByVal SlotDate As DateTime = Nothing

  If Not SlotDate = Nothing Then
       /* code to execute when date passed */
  Else
       /* code to execute when there is no date passed */
  End If

VB

Public Sub ExampleSub(Test As String, _
                      Optional fromDate As System.Nullable(Of DateTime) = Nothing)
    'A Great sub!
    If fromDate Is Nothing Then
        'code here for no fromDate
        'i.e. Now
        fromDate = DateTime.Now
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM