Search code examples
c#readability

Which is the better "if statement" to use in C#


Both these methods work, however which is better method to use out of the following:

PlaceHolder PH = ctl.PlaceHoldNu == 1 ? (PlaceHolder)Page.Master.FindControl("PlaceHolder1") : (PlaceHolder)FindControl("PlaceHolder" + ctl.PlaceHoldNu);

Or

           PlaceHolder PH;
                    if (ctl.PlaceHoldNu == 1)
                        PH = (PlaceHolder)Page.Master.FindControl("PlaceHolder1");
                    else
                        PH = (PlaceHolder)FindControl("PlaceHolder" + ctl.PlaceHoldNu);

Solution

  • Another solution would be:

    PlaceHolder PH = ctl.PlaceHoldNu == 1
        ? (PlaceHolder)Page.Master.FindControl("PlaceHolder1") 
        : (PlaceHolder)FindControl("PlaceHolder" + ctl.PlaceHoldNu);
    

    This solutions uses a minimum of lines but maintains readability.