I see this a lot:
public int CompanyID
{
get
{
if (ViewState["CompanyID"] == null)
{
ViewState["CompanyID "] = 0;
}
return int.Parse(ViewState["CompanyID "].ToString());
}
set { ViewState["CompanyID "] = value; }
}
What is wrong with it? 2 things:
1. ViewState stores and returns an object so the get{} portion of the property that first converts this to a string and then parses it back to an integer is rather inefficient.
2. This particular property is wrapping a value type (int) and as such, there is no need to persist the default value in ViewState. This unnecessarily adds to the size of ViewState on a page. A better approach would be to return the default value (or any value you choose) when the ViewState object is null.
So, a better solution:
public int CompanyID
{
get { return (int)(ViewState["CompanyID"] ?? 0); }
set { ViewState["CompanyID"] = value; }
}
Remember that the C# coalescing operator (??) returns the left side value if said value is non-null and the right side value when the left side is null. We don't create an entry in ViewState until we assign a non-nulll value.
One thing to watch out for when using this pattern is when storing certain reference types in the ViewState object.
private Dictionary<Guid, bool> ToAttach
{
get
{
if (ViewState["ToAttach"] == null)
{
ViewState["ToAttach "] = new Dictionary<Guid, bool>();
}
return (Dictionary<Guid, bool>)ViewState["ToAttach "];
}
set { ViewState["ToAttach "] = value; }
}
Testing for null and assigning an empty dictionary in the get{} portion of the property insures that we always return the same object once it is newed up. If we didn’t perform this test and tried using the coalescing operator as we did with the value type above, we would return a different object each time the property is reference and any code attempting to manipulate the object without explicitly setting the value would fail.