# Is this a proper way to check a viewstate of type int?

In page load I'm saving a query string int value in a viewstate. Then I save it to my DB. Here is the code I use to retrieve viewstate value and validating it:

protected int CurrentCom
{
get
{
if (ViewState["CurrentCom"] == null)
return 0;
else
{
int temp;
if (int.TryParse(ViewState["CurrentCom"].ToString(), out temp))
return temp;
else return 0;
}

}
set { ViewState["CurrentCom"] = value; }
}


Is there a better way to make this shorter?

I usually do like this:

return (int)(ViewState["CurrentCom"] ?? 0);

• cool ! where was this all this time ? thank you Mattias – mohsen dorparasti Jan 11 '12 at 15:38
• I would usually do return ViewState["CurrentCom"] as int? ?? 0, but this feels much better. :) – ANeves Jan 11 '12 at 17:15

I'm not too familiar with C#, but the else branch looks unnecessary, since if ViewState["CurrentCom"] == null is true the method returns with 0.

if (ViewState["CurrentCom"] == null) {
return 0;
}
int currentCom;
if (int.TryParse(ViewState["CurrentCom"].ToString(), out currentCom)) {
return currentCom;
}
return 0;