-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?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
  • 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. – Jethro Aug 15 '11 at 10:22

4 Answers4

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; }
}
jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • 1
    yes (I changed it too in the code example), but I answered the question which asked why the ***setter*** was generating stack overflow. – jgauffin Aug 15 '11 at 10:28
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; }
}
Chris Snowden
  • 4,982
  • 1
  • 25
  • 34
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

Jethro
  • 5,896
  • 3
  • 23
  • 24
Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
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.

sll
  • 61,540
  • 22
  • 104
  • 156