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\$

2 Answers 2

6
\$\begingroup\$

I usually do like this:

return (int)(ViewState["CurrentCom"] ?? 0);
\$\endgroup\$
2
  • \$\begingroup\$ cool ! where was this all this time ? thank you Mattias \$\endgroup\$ Commented Jan 11, 2012 at 15:38
  • \$\begingroup\$ I would usually do return ViewState["CurrentCom"] as int? ?? 0, but this feels much better. :) \$\endgroup\$
    – ANeves
    Commented Jan 11, 2012 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;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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