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();
}
}
StackOverflowException is thrown for execution stack overflow errors, typically in case of a very deep or unbounded recursion. So make sure your code doesn't have an infinite loop or infinite recursion.
A StackOverflowException is thrown when the execution stack overflows because it contains too many nested method calls. using System; namespace temp { class Program { static void Main(string[] args) { Main(args); // Oops, this recursion won't stop. } } }
Applying the HandleProcessCorruptedStateExceptionsAttribute attribute to a method that throws a StackOverflowException has no effect. You still cannot handle the exception from user code.
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;
}
}
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With