Exception in C # setter

It’s easy to explain: it 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"); } } } 

is 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 an exception to the second class setter, and I don't know why. I cannot use the first form because it is not supported by the unit engine.

+7
c # callstack stack-overflow setter
source share
4 answers

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

To use non-automatic properties, you need to create a separate private support field, for example:

 ConstraintSet a; public ConstraintSet A { get { return a; } set { a = value; } } 
+24
source share

You did not specify a backup variable - you have a property whose getters and setters call themselves. It is not clear to me why the first form is not supported by Unity, which means that the equivalent is not supported, but basically this:

 private ConstraintSet aValue; public ConstraintSet a { get { return aValue; } set { aValue = value; } } 

I would usually have a more conditional name, of course, which means that you can leave without the value bit:

 private ConstraintSet constraints; public ConstraintSet Constraints { get { return constraints; } set { constraints = value; } } 

To give more details on why your current second form throws a StackOverflowException , you should always remember that properties are mostly masked. Your broken code is as follows:

 public ConstraintSet get_a() { return get_a(); } public void set_a(ConstraintSet value) { set_a(value); } 

Hopefully this is obvious why this version is blowing onto the stack. The modified version simply sets the variable instead of calling the property again, so when expanded, it looks like this:

 private ConstraintSet aValue; public ConstraintSet get_a() { return aValue; } public void set_a(ConstraintSet value) { aValue = value; } 
+15
source share

Your public property needs a private backup variable:

 private ConstraintSet _a; public ConstraintSet a { get { return _a; } set { _a = value; } } 
+3
source share

You cannot use the same variable name inside getter and setter.
This will cause him to call himself and, ultimately, go to stackoverflow. Too much recursion. You will need a backup variable:

 private ConstraintSet _a; public ConstraintSet a { get { return _a; } set { _a = value; } } 
+3
source share

All Articles