When working in ASP.Net there is often the need to store an object between page postbacks which is accomplished using ViewState. Sometimes the object happens to be a property of the subclassed Page or UserControl and I’ve noticed that a lot of people use this below technique.
Bad:
public ObjectType PropertyName
{
get
{
ObjectType obj = this.ViewState["PropertyName"] as ObjectType;
if( obj == null )
{
obj = new GetFromDataBase(); // or = new ObjectType();
}
return obj;
}
set
{
this.ViewState["PropertyName"] = value;
}
}
Problems:
Every time the property is accessed you either load from ViewState and cast or save to ViewState. (performance hit)
If GetFromDataBase() returns null you will be accessing the database on every get. (performance hit)
If you instead instantise the object the property can never be null. (bad logic)
Good:
ObjectType _PropertyName;
private void Page_Load(object sender, System.EventArgs e)
{
if (!this.IsPostBack)
{
_PropertyName = GetFromDataBase(); // or = new ObjectType();
}
}
public ObjectType PropertyName
{
get
{
return _PropertyName;
}
set
{
_PropertyName = value;
}
}
protected override object SaveViewState()
{
this.ViewState["PropertyName"] = _PropertyName;
return base.SaveViewState ();
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState (savedState);
_PropertyName = this.ViewState["PropertyName"] as ObjectType;
}