21

My program throws this exception:

System.StackOverflowException

when the compiler executes the set property.

The 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; } } } 

The 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(); } } 
1
  • 2
    You need to use a backing field e.g. private int _price and then set that to the value e.g set { _price = value; } Commented Jun 2, 2016 at 15:39

3 Answers 3

27

When setting the price property, you invoke the setter, which invokes the setter which invokes the setter, etc..

Solution:

public int _price; public int price { get { return no * 5; } set { _price = value; } } 
Sign up to request clarification or add additional context in comments.

Comments

13

You're setting the value of the setter from within the setter. This is an infinite loop, hence the StackOverflowException.

You probably meant to use a backing field no as per your getter:

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

or perhaps use its own backing field.

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

However, if the latter is the case, you dont need the backing field at all, you can use an auto property:

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

(Side note: Properties should start with an uppercase - Price not price)

Comments

1

Your property setter calls itself when you set any value, thus it produces an stack overflow, I think what you wanted to do was:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.