I wrote previously about a pattern using the coalescing operator (??) that I use to wrap ViewState:
public string Title
{
get { return (string)ViewState["title"] ?? "Default title"; }
set { ViewState["title"] = value; }
}
and
public string TitleID
{
get { return (int?)ViewState["titleID"] ?? -1; }
set { ViewState["titleID"] = value; }
}
In the latter case, int is a value type and I thought the only way you could get things to work was to cast the ViewState to a nullable int type (int?), but there is a better solution:
public string TitleID
{
get { return (int)(ViewState["titleID"] ?? -1); }
set { ViewState["titleID"] = value; }
}
The difference is subtle but ViewState is an object type and you can apply the coalescing operator directly to it. Then cast that result to an int.
-Andrew