开发者

Better syntax for a return statement in a method which retrieves a query String

开发者 https://www.devze.com 2023-03-28 11:03 出处:网络
I use this simple method to retrieve a Query String from a Page a returning a Int. In case a valid Id can not be found I 开发者_如何转开发would like return a default value int 0.

I use this simple method to retrieve a Query String from a Page a returning a Int. In case a valid Id can not be found I 开发者_如何转开发would like return a default value int 0.

I would like to know if there is a better way to write this method, in details:

  • Would be better use just a single return statement instead the two? If yes what is the best way to do it?
  • Shall I perform any other checking when retrieving the Query String?
protected int GetPageIndex()
{
    int output;
    bool result = Int32.TryParse(Request.QueryString["page"], out output);
    if(result)
        return output;
    return output = 0; // Return Default value
}


Just initialize it before you try to parse it... Anyways, Int32.TryParse sets the value to 0 if the conversion is unsuccessful... :) http://msdn.microsoft.com/en-us/library/f02979c7.aspx

protected int GetPageIndex()
    {
        int output = 0;
        Int32.TryParse(Request.QueryString["page"], out output);
        return output;
    }


You're safe to simply return output, since you're seemingly not concerned as to whether TryParse succeeded or not, and by assigning a value of 0 to output initially, for clarity, then that is what will be returned if TryParse fails anyway.

protected int GetPageIndex()
{
    int output = 0;
    int.TryParse(Request.QueryString["page"], out output);
    return output;
}


How about this to use less code, with regards to checking the query string I dont think you need to check for null as the try parse should handle the null value.

protected int GetPageIndex()
{
    int output;
    return Int32.TryParse( Request.QueryString[ "page" ], out output ) ? output : 0;
}


int output;
return Int32.TryParse(Request.QueryString["page"], out output) ? output : 0;


I'd go with

protected int GetPageIndex()
{
    int output = 0;
    Int32.TryParse(Request.QueryString["page"], out output);
    return output; 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消