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
  • 862
  • 1
  • 16
  • 36

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
  • 57,045
  • 27
  • 167
  • 292
Chris Gessler
  • 22,017
  • 6
  • 53
  • 80
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,140
  • 3
  • 37
  • 61