1

I have an DateTime property field in a struct. I'm trying to validate the inputdate to make sure the value entered is not in the future.

i'm using the following code:

public struct Car
{
    public DateTime Year
    {
        get
        {
            return Year;
        }

        set
        {
            if (value > DateTime.Now)
                throw new InvalidOperationException("Date cannot be in the futrure");
            else
                Year = value;
        }
    }
}

When i now try to run this code i keep getting a StackOverflowException with the message "Cannot evaluate expression because the current thread is in a stack overflow state."

any ideas on why this is, or how to fix this?

-Thanks.

zaza
  • 892
  • 1
  • 18
  • 37

2 Answers2

4

It's returning itself... try setting a variable.

public struct Car 
{ 
    private DateTime _year;
    public DateTime Year 
    { 
        get 
        { 
            return _year; 
        } 

        set 
        { 
            if (value > DateTime.Now) 
                throw new InvalidOperationException("Date cannot be in the futrure"); 
            else 
                _year = value; 
        } 
    } 
} 
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
Chris Gessler
  • 22,727
  • 7
  • 57
  • 83
4

You're calling a property called Year, whose get accessor calls Year, whose get accessor calls Year... and so on, and so forth, until your stack overflows.

You should create a private field, private DateTime _year, to store the actual value.

Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63