An exception of type "System.StackOverflowException" is thrown

My program throws this exception:

System.QaruException

when the compiler executes the set property.

wine class:

 class wine { public int year; public string name; public static int no = 5; public wine(int x, string y) { year = x; name = y; no++; } public int price { get { return no * 5; } set { price = value; } } } 

Program Class:

 class Program { static void Main(string[] args) { wine w1 = new wine(1820, "Jack Daniels"); Console.WriteLine("price is " + w1.price); w1.price = 90; Console.WriteLine(w1.price); Console.ReadLine(); } } 
+10
source share
3 answers

When setting the price property, you call the installer, which calls the installer, which calls the setter, etc.

Decision:

 public int _price; public int price { get { return no * 5; } set { _price = value; } } 
+16
source

You set the setter from the setter. This is an infinite loop, therefore a StackOverflowException exception.

You probably used the background field no according to your recipient:

 public int price { get { return no * 5; } set { no = value/5; } } 

or perhaps use your own support field.

 private int _price; public int price { get { return _price; } set { _price = value;; } } 

However, if the latter is the case, you do not need a support field at all, you can use the auto property:

 public int price { get; set; } // same as above code! 

(Side note: properties must start with an uppercase - Price not Price )

+9
source

Your property setter calls itself when you set a value, so it creates a stack overflow, I think you would like to do:

 public int price { get { return no * 5; } set { no = value / 5; } } 
0
source

All Articles