Stack overflow exception in C# setter

Patrik picture Patrik · Jul 18, 2010 · Viewed 9.8k times · Source

This works:

using System;
using ConstraintSet = System.Collections.Generic.Dictionary<System.String, double>;

namespace ConsoleApplication2
{
    class test
    {
        public ConstraintSet a { get; set; }
        public test()
        {
            a = new ConstraintSet();
        }
        static void Main(string[] args)
        {
            test abc = new test();
            Console.WriteLine("done");
        }
    }
}

This does not:

using System;
using ConstraintSet = System.Collections.Generic.Dictionary<System.String, double>;

namespace ConsoleApplication2
{
    class test
    {
        public ConstraintSet a { get { return a; } set { a = value; } }
        public test()
        {
            a = new ConstraintSet();
        }
        static void Main(string[] args)
        {
            test abc = new test();
            Console.WriteLine("done");
        }
    }
}

I get a stack overflow exception on a's setter in the second class and I do not know why. I cannot use the first form because it is not supported by the Unity game engine.

Answer

SLaks picture SLaks · Jul 18, 2010

When you write a = value, you are calling the property setter again.

In order to use non-automatic properties, you need to create a separate private backing field, like this:

ConstraintSet a;
public ConstraintSet A { get { return a; } set { a = value; } }