How can I create an optional DateTime parameter?

北城余情 提交于 2019-12-05 01:02:57

One workaround is to assign them like this:

public DateTime GetDate(DateTime? start = null, DateTime? end = null){
    start = start ?? DateTime.MinValue;
    end = end ?? DateTime.MinValue;

    Console.WriteLine ("start: " + start);
    Console.WriteLine ("end: " + end);
    return DateTime.UtcNow;
}

Which can be used like this:

void Main()
{
    new Test().GetDate();
    new Test().GetDate(start: DateTime.UtcNow);
    new Test().GetDate(end: DateTime.UtcNow);
    new Test().GetDate(DateTime.UtcNow, DateTime.UtcNow);
}

And works just as expected:

start: 1/01/0001 0:00:00
end: 1/01/0001 0:00:00

start: 8/08/2014 17:30:29
end: 1/01/0001 0:00:00

start: 1/01/0001 0:00:00
end: 8/08/2014 17:30:29

start: 8/08/2014 17:30:29
end: 8/08/2014 17:30:29

Note the named parameter to distinguish between the start and end value.

Btw, you don't have to use nullable datetime like all other answers says. You can do it with DateTime as well:

public DateTime GetDate(
     DateTime start = default(DateTime), 
     DateTime end = default(DateTime))
{
     start = start == default(DateTime) ? DateTime.MinValue : start;
     end = end == default(DateTime) ? DateTime.MinValue : end;
}

This is unlikely but it won't work as expected if you actually pass the default datetime value to your function.

You can set the DateTime to be nullable and then convert to DateTime.Min if no parameter is provided:

public DateTime GetDate(DateTime? start = null, DateTime? end = null) {
    var actualStart = start ?? DateTime.Min;
    var actualEnd = end ?? DateTime.Min;
}

The only way would be to do it like this (a bit more code, but it gives you optional args):

public DateTime GetDate(DateTime? start = null, DateTime? end = null)
{
    // Method body...
    if(start == null)
    {
      start = DateTime.MinValue;
    }

    //same for end
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!