Exception of type 'System.StackOverflowException' was thrown

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)


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

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

Tags:

C#