I get into an endless loop in setting properties

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

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

+5
source share
4 answers

The error is that in yours set {}you call the same setter recursively.

The correct code will 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;
    }
}
+13
source

Use a member variable, or possibly save it in a 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;
    }
}
+4
source

.

KISS -

public int Position
{
  get { return (int) ( Session["Position"] ?? 5 ) ; }
  set { Session["Position"] = value ;               }
}

( /:

public int Position
{
  get { return Session["Pointer"] as int? ?? position ?? 5 ; }
  set { position = value ; }
}
private int? position ; // backing store
+2

- , . , .

Your getter calls the setter, and the setter calls setter; it will be infinite recursion. You may need a storage box Position.

However, if we change it with saving in the field, and the setter does not actually affect. Thus, the code can be changed to:

public int Position {
    set {
    }

    get {
        int x;
        return (x=Convert.ToInt32(Session["Position"]))>0?x:5;
    }
}

You do not need to check for null, which Convert.ToInt32(null)is zero.

+1
source

All Articles