0

I have an object in C# which has current property.

public DateTime startDate
{
    get 
    {
        string[] ymd = Environment.GetCommandLineArgs()[2].Split('.');
        return new DateTime(Int32.Parse(ymd[2]), Int32.Parse(ymd[1]), Int32.Parse(ymd[0])); 
    }
    set { startDate = value; }
}

But when I try to use the function defined as this:

public String Calculate(){
    if (startDate > endDate)
        return "not calculable since the end date can not be before than the start date.";

    while (startDate <= endDate)
    {
        if (startDate.DayOfWeek.ToString()[0] != 'S')
            count++;
        startDate = startDate.AddDays(1);
    }

    return "not implemented yet";

Stack Overflow occurs :) Can you help me fix this?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • 1
    Note that this has nothing to do with `DateTime`. It's a simple problem with your setter which could have been avoided by using a better naming convention. – John Saunders Sep 02 '14 at 19:34

2 Answers2

7

There is a mistake in your setter. You're trying to assign to the same property, that's the cause of the stack overflow, as every assignment to a property is just calling it's setter.

set { startDate = value; }
Eldar Dordzhiev
  • 5,105
  • 2
  • 22
  • 26
1

The property is setting itself here, causing an infinite loop:

set { startDate = value; }

You would need a backing field to keep the value of the property, and initialise it if it hasn't been set:

private DateTime? _startDate;

public DateTime startDate {
  get {
    if (!_startDate.HasValue) {
      string[] ymd = Environment.GetCommandLineArgs()[2].Split('.');
      _startDate = new DateTime(Int32.Parse(ymd[2]), Int32.Parse(ymd[1]), Int32.Parse(ymd[0]));
    }
    return _startDate.Value;
  }
  set { _startDate = value; }
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005