-2

The stack overflow exception was thrown in the setter method of this property:

public string TimeZone
{
    get
    {
        if (TimeZone == null)
            return "";

        return TimeZone;
    }
    set { TimeZone = value; }
}

"An unhandled exception of type 'System.StackOverflowException' occurred"

I do not see any straightforward recursion here.

If there are problems with the code, what should I be using instead to correct it?

1
  • As jgauffin stated below, when you call return TimeZone what is actually happening is you are calling the TimeZone property again. So it goes into an infinite loop, always calling it's self again and again. Commented Aug 15, 2011 at 10:22

4 Answers 4

11
set { TimeZone = value; }

The setter is recursive.

You must use a field like:

string _timeZone;

public string TimeZone
{
    get
    {
        if (_timeZone== null)
            return "";

        return _timeZone;
    }
    set { _timeZone= value; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

yes (I changed it too in the code example), but I answered the question which asked why the setter was generating stack overflow.
4

Both get and set are recursive by calling themselves again. Try this instead:

string timeZone;

public string TimeZone
{
    get { return timeZone == null ? string.Empty : timeZone; }
    set { timeZone = value; }
}

Comments

1

Try this

  public string TimeZone
    {
        get
        {
            if (m_TimeZone == null)
                return "";

            return m_TimeZone;
        }
        set {m_TimeZone = value; }
    }

Where m_TimeZoneshould be associated variable

you are accessing same property TimeZone inside property TimeZone where you should be accessing and using associated variable

Comments

1

In getter you ara accessing getter itself, this cause a recursive call to property getter itself

 if (TimeZone == null) 

Setter recursive as well

set { TimeZone = value; } 

So depends on calling code either getter or setter cause an stack overflow due to multiple calls to property (get_TimeZone() / set_TimeZone() methods under the hood).

So introduce backing field and use it in property, this is a commo technique I'm wondered why you are not aware of such simple stuff.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.