Iron Academy Logo
Learn C#

C# Switch Case

Layla Porter
20m 21s

The switch statement in C# is a powerful control flow mechanism that allows developers to execute one block of code among many based on the value of the expression. It is particularly useful for situations where multiple conditions need to be checked against a single variable. Operators can be employed within switch cases to perform various actions on match expression, such as comparisons and logical checks.

Layla Porter, in her video on "C# for Beginners part 4 - Operators and Switches", dives into fundamental concepts in C# programming, focusing on operators and switch case statements. This article, inspired by her video, will break down her explanations and provide code snippets from her video to understand switch case and operators.

Introduction to Operators

Operators in C# are crucial for manipulating data, comparison between two values and making decision based case values and on comparisons.Layla begins by explaining different types of operators: arithmetic, comparison, and logical operators.

User Input Using Console.ReadLine

Layla starts by demonstrating how to capture user input using Console.ReadLine(). This method reads a line of input from the console, which is essential for interactive C# applications.

Console.WriteLine("Hello, please write any word:");
string word = Console.ReadLine();
Console.WriteLine("Hello, please write any word:");
string word = Console.ReadLine();

Assignment Operator

In the above code snippet, Layla uses assignment operator (=) to store the value obtained from user input into the variable word. Here's a breakdown:

  • string word: Declares a variable named word of type string.

  • word = Console.ReadLine(): Uses the assignment operator (=) to assign the value entered by the user (obtained from Console.ReadLine()) to the word variable.

In this context, the assignment operator is used to set the value of the variable word to whatever the user types in the console. The assignment operator is fundamental in programming, as it is used to store values in variables, allowing those values to be used and manipulated throughout the execution of the program.

Arithmetic Operators

Arithmetic operators in C# perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus. These operators are straightforward and essential for any programming language. Layla doesn't cover these in her video because these are simple math operations that return the same exact values as in real math problems.

Comparison Operators

Comparison operators in C# allow us to compare values and make decisions based on those comparisons. Layla introduces the greater than (>), less than (<), greater than or equal to (>=), less than or equal to (<=), equality (==), and inequality (!=) operators.

Using Comparison Operators in Conditional Logic Statements

In her video, Layla Porter dives into using conditional logic in C# to determine the length of a word provided by the user. She at 2:10, starts by demonstrating the basic structure of an if statement to check the length of a string using the Length property of the string type. This property returns the number of characters in the string.

if (word.Length < 6)
{
    Console.WriteLine("That's a short word.");
}
if (word.Length < 6)
{
    Console.WriteLine("That's a short word.");
}

The first conditional check uses the less than (<) operator to see if the word's length is less than six characters. If the condition is true, the program outputs, "That's a short word." This part of the code helps categorize shorter words effectively.

Next, at 4:00 Layla Porter introduces the concept of using an else if statement with combined conditions using the greater than or equal to (>=) operator and the logical AND (&&) operator. The combined condition checks if the word length is at least six but less than eleven characters. If both conditions are satisfied, the program outputs, "That's a medium length word." This shows how multiple conditions can be combined to make more refined decisions based on the word length.

else if (word.Length >= 6 && word.Length < 11)
{
    Console.WriteLine("That's a medium length word.");
}
else if (word.Length >= 6 && word.Length < 11)
{
    Console.WriteLine("That's a medium length word.");
}

Finally, Layla at 4:40, explains the use of the else statement to handle all other cases that do not meet the previous conditions. This part of the code outputs, "That's a long word." for words that are eleven characters or longer. Using the else statement ensures that any input not caught by the preceding conditions is handled appropriately.

else
{
    Console.WriteLine("That's a long word.");
}
else
{
    Console.WriteLine("That's a long word.");
}

Now, Layla runs the program (5:15) and input some words to categorize using the above conditional statements and Comparison operators:

Logical Operators

Logical operators (&&, ||, !) allow combining multiple conditions in C# to create more complex decision-making logic. Layla at 6:24, explains how these operators work together to create conditional statements.

In her video, Layla Porter introduces a mini-game where the user is asked to identify the odd word out from a list of animals: "dog," "cat," and "goldfish." Goldfish is considered the odd one out because it lives in water and is not a mammal. Layla (6:55) starts by asking the user to input their choice using Console.ReadLine() and then ensures the input is in lowercase using the ToLower() method to avoid case sensitivity issues when comparing strings:

Console.WriteLine("Pick the odd one out - dog, cat, goldfish");
string oddOne = Console.ReadLine().ToLower();
Console.WriteLine("Pick the odd one out - dog, cat, goldfish");
string oddOne = Console.ReadLine().ToLower();

Layla at 7:32, explains the use of the comparison operators to check the user's input against the system and predefined list of animals.

if (oddOne != "dog" && oddOne != "cat")
{
    Console.WriteLine("You chose the odd one out!");
}
if (oddOne != "dog" && oddOne != "cat")
{
    Console.WriteLine("You chose the odd one out!");
}

The code uses the not equal to (!=) operator to check if the input does not match "dog" and "cat." By combining these conditions with the logical AND (&&) operator, the code ensures both conditions must be true for the statement to be satisfied. If the input is neither "dog" nor "cat," it must be "goldfish," and the program outputs, "You chose the odd one out!"

else
{
    Console.WriteLine("Better luck next time!");
}
else
{
    Console.WriteLine("Better luck next time!");
}

If the user's input does not satisfy this condition, meaning the input is either "dog" or "cat," the else block executes, and the program outputs the error of, "Better luck next time!"

Layla (8:30) further elaborates on the importance of understanding how logical operators work in conditional statements. The AND operator (&&) requires both conditions to be true, while the OR operator (||) requires only one condition to be true. She (9:05) demonstrates how using these operators can change the program's behavior, highlighting the nuances and potential pitfalls when using logical operators in C#. This explanation helps viewers understand how to effectively use conditional logic in their programs.

Introduction to C# Switch Case Statements

Switch statements provide an alternative way to implement multi-branch decision-making in C#, often more readable and efficient than multiple if-else statements. In C#, 'case c' is used to specify conditions within switch statements, ensuring that the comparison operates on values of the same type.

In her video (12:38), Layla Porter transitions from using an if-else statement to a switch statement to determine the length category of a given word. She explains that using a switch statement can make the code cleaner and more efficient.

The code snippet looks like this:

switch (word.Length)
{
    case < 6:
        Console.WriteLine("That's a short word!");
        break;
    case int length when 6 <= length && length < 11:
        Console.WriteLine("That's a medium length word!");
        break;
    default:
        Console.WriteLine("That's a long word!");
        break;
}
switch (word.Length)
{
    case < 6:
        Console.WriteLine("That's a short word!");
        break;
    case int length when 6 <= length && length < 11:
        Console.WriteLine("That's a medium length word!");
        break;
    default:
        Console.WriteLine("That's a long word!");
        break;
}

Layla explains that a switch statement is composed of multiple cases, each representing a possible value or range of values for the variable being evaluated. In this case, the variable is word.Length.

  1. Case < 6: The first case checks if the length of the word is less than 6. If this condition is met, the program outputs "That's a short word!" and then uses the break statement to exit the switch block. Remember the case can have multiple statements.

  2. Case int length when 6 <= length && length < 11: The second case is more complex. It uses a pattern matching feature introduced in C# 7.0. The case is defined with int length followed by a when clause that specifies additional conditions: the length must be greater than or equal to 6 and less than 11. If the patterns match, the program outputs "That's a medium length word!" and then exits the switch block.

  3. Default: If none of the previous cases are satisfied, the default case is executed. This acts like the else statement in an if-else structure. In this case, the program outputs "That's a long word!" and exits the switch block.

Layla (15:45) highlights that using a switch statement over an if statement can be beneficial because it makes the code more readable and easier to manage, especially when dealing with multiple conditions. Additionally, she mentions that switch statements can be more efficient because the C# compiler optimizes them differently, making them faster to execute.

Switch Expressions (Pattern Matching)

Switch expressions are a newer feature in C# that provides more concise syntax for simple value-based decisions. In Layla Porter's video around 16:25, she introduces a modern switch statement called a "switch expression" or "pattern matching switch" in C#. This type of switch statement returns a value directly, making the code more concise and readable.

She (around 17:00) begins by showing how to rewrite an if-else statement using the switch expression syntax. Instead of performing actions, the switch expression assigns a value to a variable based on conditions. For instance this example:

// Example of Switch Expression
string message = word.Length switch
{
    < 6 => "That's a short word!",
    < 11 and >= 6 => "That's a medium length word!",
    _ => "That's a long length word!"
};

Console.WriteLine(message);
// Example of Switch Expression
string message = word.Length switch
{
    < 6 => "That's a short word!",
    < 11 and >= 6 => "That's a medium length word!",
    _ => "That's a long length word!"
};

Console.WriteLine(message);

Here's what Layla (17:31) explains about the above code:

  1. String message = word.Length switch: Initializes a string variable message and starts a switch expression based on word.Length.

  2. < 6 => "That's a short word!": If word.Length is less than 6, it returns "That's a short word!" using the less-than operator <.

  3. < 11 and >= 6 => "That's a medium length word!": If word.Length is between 6 and 10 inclusive, it returns "That's a medium length word!" using and for readability. (and-for) ?

  4. **=> "That's a long length word!"**: The underscore serves as a default case, returning "That's a long length word!" if none of the previous conditions are met.

Layla emphasizes that this syntax is part of modern C# features designed to improve readability and efficiency. The switch expression is preferred over traditional if-else statements for handling multiple conditions concisely.

She runs the code at 19:30 and the output is the same as for if-else: (Image can be better?)

Conclusion

Layla Porter’s video provides a solid foundation for beginners in C# programming, covering essential concepts like operators, conditional statements, and switch statements. By following along with her explanations and examples, beginners can gain practical insights into how to manipulate data and control program flow effectively in C#.

By understanding these fundamental concepts and practicing with the provided examples, newcomers to C# can build a strong foundation for more complex programming tasks. Check out more C# videos on her YouTube Channel.