Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am getting into infinite loop in property setter

public int Position
{
    get
    {
        if (Session["Position"] != null)
        {
            Position = Convert.ToInt32(Session["Position"]);
        }
        else
        {
            Position = 5;
        }
        return Position;
    }
    set
    {
        Position = value;
    }
}

my program calls the get and goes into if loop and then runs infitely into set code

like image 926
Ben Avatar asked Apr 22 '13 19:04

Ben


2 Answers

The error is because in your set {} you are invoking the same setter recursively.

Correct code would be

private int _position;
public int Position
{
    get
    {
        if (Session["Position"] != null)
        {
            this._position = Convert.ToInt32(Session["Position"]);
        }
        else
        {
            this._position = 5;
        }
        return this._position;
    }
    set
    {
        this._position = value;
    }
}
like image 81
Knaģis Avatar answered Sep 24 '22 21:09

Knaģis


Use a member variable or perhaps store it in the session.

private int _position;
public int Position
{
    get
    {
        if (Session["Position"] != null)
        {
            _position= Convert.ToInt32(Session["Position"]);
        }
        else
        {
            _position= 5;
        }
        return _position;
    }
    set
    {
        _position = value;
    }
}
like image 26
Daniel A. White Avatar answered Sep 23 '22 21:09

Daniel A. White