1

I have a method that currently takes a DateTime startDate and DateTime endDate. It would be really great if there would be a datatype that consists of two DateTime so that my method only has to take one value instead of two.

I am specifically looking for a single type, but if it's not possible I guess I have to create my own DatePeriod class.

Solution

After looking into this for some more time I finally came to realize that there is no perfect answer to my question. So now I created my own class holding the two values, a Tuple would work just as fine though.

Here's the code (almost exact same as in StepUp's Answer, but I use a struct):

public struct DatePeriod
{
    public DateTime Start { get; set; }
    public DateTime End { get; set; }

    public DatePeriod(DateTime startDate, DateTime endDate)
    {
        Start = startDate;
        End = endDate;
    }
}
baltermia
  • 1,151
  • 1
  • 11
  • 26

2 Answers2

2

One of the way is to create a class that holds necessary data:

public class FooClass
{
    public DateTime StartDate { get; private set; }
    public DateTime EndDate { get; private set; }

    public FooClass(DateTime startDate, DateTime endDate)
    {
        StartDate = startDate;
        EndDate = endDate;
    }
}

And use it as an argument:

public void YourMethod(Fooclass foo)
{
}

And an example of using Tuple

public void Tuple(Tuple<DateTime, DateTime> test) 
{}

In addition, you can read more DTO pattern.

StepUp
  • 36,391
  • 15
  • 88
  • 148
2

You can work with a self-defined model:

public class CustomDateRange
{
    public DateTime Start {get;set;}
    public DateTime End {get;set;}
}

You can work with a Tuple class:

var range = new Tuple <DateTime, DateTime>(start, end)

Or you can even work with a Tuple type:

(DateTime, DateTime) range = (start, end)

Perhaps there are even more options, but these are the ones that came to my mind atm.

mvesign
  • 41
  • 5