public int Position
{
get
{
if (Session[\"Position\"] != null)
{
Position = Convert.ToInt32(Session[\"Position\"]);
}
There's nothing particularly string-like about session state items.
Why wouldn't you just follow the KISS principle and do something like
public int Position
{
get { return (int) ( Session["Position"] ?? 5 ) ; }
set { Session["Position"] = value ; }
}
or (depending on your actual requirements/specs:
public int Position
{
get { return Session["Pointer"] as int? ?? position ?? 5 ; }
set { position = value ; }
}
private int? position ; // backing store
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;
}
}
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;
}
}
An auto-implemented property property consists of a getter, a setter and a backing field. If you write the code yourself, a field might not be necessary.
Your getter invokes setter, and the setter invokes setter; that would be infinite recursion. You might need a field for storing Position
.
However, if we change it with storing to a field, and the setter in fact doesn't effect. So, the code could be changed to:
public int Position {
set {
}
get {
int x;
return (x=Convert.ToInt32(Session["Position"]))>0?x:5;
}
}
You don't need to check for null, Convert.ToInt32(null)
is zero.