Skip to content
Loading
  • Anil Jha
    +2
    To remove if-else statement in C#, you can use ternary operator or switch - case statement.
    I would suggest you to achieve it using decoulpled architure using Dependency injection. 
    +2
  • Ramesh Barik
    0
    You can use switch-statement instade of if. switch is more perfermance tuned.
    Check this link to know more.
    https://stackoverflow.com/questions/2158759/case-vs-if-else-if-which-is-more-efficient 
    0
  • Abhilash J A
    0
    Okay, Let's say...
     
    1. public string GetAdvertisementType(string type)  
    2.        {  
    3.            switch (type)  
    4.            {  
    5.                case "PS":  
    6.                    return "Product search";  
    7.                    break;  
    8.                case "SS":  
    9.                    return "Services search";  
    10.                    break;  
    11.                case "ST":  
    12.                    return "Scrollable  text";  
    13.                    break;  
    14.                default:  
    15.                    return "";  
    16.                    break;  
    17.            }  
    18.        } 
     Cheers !!!
    0
  • Nimish Saxena
    0
    You can use ternary operator.
    for eg:- var res=a == "something"?"something1":"something2" ;
    this produce same result as if else.
    0
  • Ibrahim Siddique
    0
    you can use two option one is  ternary operator and the second one is Switch case 
     
     
     
    1. Example :
    C#
    int result = Check() ? 1 : 0;
     
     
     
    2. Example :
     
    Code
    switch (grade)
    Code
     { case 'A': Console.WriteLine("Excellent!"); break;
    Code
    case 'B': Console.WriteLine("Good Job!"); break;
    Code
     case 'C': Console.WriteLine("Well done"); break;
    Code
     case 'D': Console.WriteLine("You passed"); break;
    Code
     case 'F': Console.WriteLine("Better try again"); break;
    Code
    default: Console.WriteLine("Invalid grade"); break; }
     
    0
  • Naveen Bisht
    0
    if I will use switch instead of if the thing is same except performance only I want to remove line of if -else and write a generic code for same
    0
  • 0

    Simple way -Use switch case.

    Advanced with few lines of code -Use any pattern suitable to your case .e.g -Strategy pattern

    0
  • Satyaprakash Samantaray
    0
    Use switch case
    0
  • Sivasankar Gorantla
    0
    Hi,
     
    - If you have two conditions then go for "Ternary" operator.
     
    - If you have multiple if statements in your code then it is better to convert them into switch statements. switch statement is faster than if statement in many cases. Because it internally implements hashtable for lookups. 
     
    Thanks,
    Siva 
    0
  • Jamil Moughal
    0
    You can avoid multiple if statements by using Switch statement or ternary operators
    0