0

Am I doing something very silly here, fromDate value always remains what has been passed.

public List<String> GetDates(DateTime fromDate, DateTime toDate)
{
    List<String> Dates = new List<String>();
    while (fromDate <= toDate)
    {
        Dates.Add(fromDate.ToShortDateString());
        fromDate.AddDays(1);
    }
    return Dates;
}

I can't figure out why, Please advise.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
Learner
  • 776
  • 6
  • 14
  • 40
  • Your post missing link to MSDN article for `DateTime.AddDays` and explanation what you don't understand from it, or maybe links to top couple result from search like https://www.bing.com/search?q=DateTime.AddDays with corresponding explanations what additional information is needed. – Alexei Levenkov Jun 01 '15 at 00:36

3 Answers3

4

you need to assign to fromDate, AddDays() does not modify the instance on which it is called:

fromDate = fromDate.AddDays(1);
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
3

If you look at the method description of .AddDays, you'll see that it actually returns a datetime object, it does not actually modify the variable in which AddDays is being called.

You can get your desired behavior by:

fromDate = fromDate.AddDays(1);

See more info at:

https://msdn.microsoft.com/en-us/library/system.datetime.adddays%28v=vs.110%29.aspx

Kritner
  • 13,557
  • 10
  • 46
  • 72
2

The MSDN Help for AddDays has the following sentence worth noting, towards the end of the page under "Remarks":

This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation.

Simply store the returned DateTime object and you are good to go.

fromDate = fromDate.AddDays(1);