简体   繁体   中英

Optimize conditional operators branching in C#

return this.AllowChooseAny.Value ? radioSpecific.Checked ? UserManager.CurrentUser.IsClient ? txtSubject.Text : subjectDropDownList.SelectedItem.Text : String.Empty : UserManager.CurrentUser.IsClient ? txtSubject.Text : subjectDropDownList.SelectedItem.Text;

or in less complex form:

return any ?
    specified ?
       isClient ? textbox : dropdown :
       empty :
    isClient ? textbox : dropdown;

or in schematic form:

                     |
                    any
              /            \
      specified             isClient
      /        \           /        \
  isClient    empty     textbox  dropdown
  /       \
textbox  dropdown

Evidently I have a duplicated block on two different levels. Is it possible to optimize this code to probably split them to one? Or something like that..

That block of code is nearly unreadable. Don't use the ternary operator just for the sake of the ternary operator; it's there to make thigs more readable by eliminating if blocks for very simple expressions. What you have is not.

You can simplify your expression to this:

if (any && !specified)
{
    return empty;
}
else
{
    return isClient ? textbox : dropdown;
}
any && !specified ? 
   empty : 
   isClient ? textbox : dropdown;  

Put the isClient ? textbox : dropdown isClient ? textbox : dropdown block in a method and make method calls from you original branch = no more code duplication.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM