4
\$\begingroup\$

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?

\$\endgroup\$
6
\$\begingroup\$

I usually do like this:

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

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;
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.