Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception of type 'System.StackOverflowException' was thrown

Tags:

c#

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();
    }
}
like image 316
user3569734 Avatar asked Jun 02 '16 15:06

user3569734


People also ask

How do I fix exception of type system StackOverflowException was thrown?

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.

What causes StackOverflowException?

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. } } }

Can we handle StackOverflowException?

Applying the HandleProcessCorruptedStateExceptionsAttribute attribute to a method that throws a StackOverflowException has no effect. You still cannot handle the exception from user code.


2 Answers

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;
    }
}
like image 67
Eyal Perry Avatar answered Sep 28 '22 04:09

Eyal Perry


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)

like image 42
Jamiec Avatar answered Sep 28 '22 06:09

Jamiec