Overloading getter and setter causes a stack overflow in C#

10,708

Solution 1

Yes, you do not have a backing field... this is how you should do it:

private MyEnumType data;

public MyEnumType Data
{
  get
  {
    return data;
  }
  set
  {
    data = value;
  }
}

What happens is that you are referring to the property to return itself, which causes an infinite loop of trying to access its own value. Hence, a stack overflow.

In your case when you do not add any additional logic in the get and set methods you could use an automatic property as well. This is simply defined like so:

public MyEnumType Data
{
  get;
  set;
}

Solution 2

You are referencing the property itself inside your getter and setter, and that causes infinite recursion (a stack overflow). It would have been more obvious if you had used the standard naming conventions (Data). Try something like:

private MyEnumType _data;

public MyEnumType Data
{
  get { return _data; }
  set { _data = value; }
}

Solution 3

public class MyClass
{
    string propertyString;

    public string MyPropertyString
    {
        get
        {
            return propertyString;
        }
        set
        {
            propertyString = value;
        }
    }
}

The name of property must be different from the member name.

Solution 4

Put a breakpoint inside the setter / getter and debug, making sure that you use step into (F11), not step over - this should help explain what's going on.

Share:
10,708
hila shmueli
Author by

hila shmueli

● System/Software Engineer, developing Web and desktop applications with broad experience in .NET and Java.

Updated on June 15, 2022

Comments

  • hila shmueli
    hila shmueli almost 2 years

    I am not sure what is causing the StackOverflowException when I try to overwrite a get and set function. When I just use the default get and set it works.

    enum MyEnumType
    {
    ....
    }
    
    public MyEnumType data { get; set; }
    

    But when I try to add additional data, it throws a StackOverflowException:

    public MyEnumType data
    {
      get
      {
        return data;
      }
      set
      {
        data = value;
      }
    }
    

    Any ideas? When I do this for ASP.NET user control attributes there isn't any problem. Why is it is causing a StackOverflowException for a normal enum data type?

  • Matthew Scharley
    Matthew Scharley over 14 years
    For those who don't know, C# implements properties under the hood as two seperate functions . Hence, each call to a setter or getter introduces another stack layer, eventually leading to a stack overflow.