- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is difference between using if/else and switch-case in C#?
Switch is a selection statement that chooses a single switch section to execute from a list of candidates based on a pattern match with the match expression.
The switch statement is often used as an alternative to an if-else construct if a single expression is tested against three or more conditions.
Switch statement is quicker. The switch statement the average number of comparisons will be one regardless of how many different cases you have So lookup of an arbitrary case is O(1)
Using Switch −
Example
class Program{ public enum Fruits { Red, Green, Blue } public static void Main(){ Fruits c = (Fruits)(new Random()).Next(0, 3); switch (c){ case Fruits.Red: Console.WriteLine("The Fruits is red"); break; case Fruits.Green: Console.WriteLine("The Fruits is green"); break; case Fruits.Blue: Console.WriteLine("The Fruits is blue"); break; default: Console.WriteLine("The Fruits is unknown."); break; } Console.ReadLine(); } Using If else class Program{ public enum Fruits { Red, Green, Blue } public static void Main(){ Fruits c = (Fruits)(new Random()).Next(0, 3); if (c == Fruits.Red) Console.WriteLine("The Fruits is red"); else if (c == Fruits.Green) Console.WriteLine("The Fruits is green"); else if (c == Fruits.Blue) Console.WriteLine("The Fruits is blue"); else Console.WriteLine("The Fruits is unknown."); Console.ReadLine(); } }
Advertisements