How can I create an optional DateTime parameter?

后端 未结 4 1051
悲哀的现实
悲哀的现实 2021-02-18 23:30

I have this function that returns a reference type. Now, this function has two optional parameters both of which are instances of the DateTime class. The function i

4条回答
  •  臣服心动
    2021-02-19 00:12

    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.

提交回复
热议问题