0
0
C Sharp (C#)programming~10 mins

Switch expressions with patterns in C Sharp (C#) - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to return the correct string for the number using a switch expression.

C Sharp (C#)
string result = number switch [1];
Drag options to blanks, or click blank then click option'
A< 1 => "One", 2 => "Two", _ => "Other" >
B( 1 => "One", 2 => "Two", _ => "Other" )
C[ 1 => "One", 2 => "Two", _ => "Other" ]
D{ 1 => "One", 2 => "Two", _ => "Other" }
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or brackets instead of curly braces for switch expression.
Forgetting the underscore (_) as the default case.
2fill in blank
medium

Complete the switch expression to return "Positive" for numbers greater than zero.

C Sharp (C#)
string result = number switch {
    > 0 => "Positive",
    0 => "Zero",
    [1] => "Negative"
};
Drag options to blanks, or click blank then click option'
A< 0
B> 0
C== 0
D>= 0
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>= 0' which overlaps with zero and positive cases.
Using '== 0' which duplicates the zero case.
3fill in blank
hard

Fix the error in the switch expression to correctly handle strings starting with 'A'.

C Sharp (C#)
string result = input switch {
    [1] => "Starts with A",
    _ => "Other"
};
Drag options to blanks, or click blank then click option'
Astring s => s.StartsWith("A")
Bstring s when s.StartsWith("A")
Cstring s if s.StartsWith("A")
Dstring s where s.StartsWith("A")
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=>' instead of 'when' for conditions.
Using 'if' or 'where' which are invalid in this context.
4fill in blank
hard

Fill both blanks to return the correct description for the shape using switch expression with type patterns.

C Sharp (C#)
string description = shape switch {
    [1] => "Circle with radius " + c.Radius,
    [2] => "Rectangle with width " + r.Width + " and height " + r.Height,
    _ => "Unknown shape"
};
Drag options to blanks, or click blank then click option'
ACircle c
BRectangle c
CRectangle r
DCircle r
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing variable names and types incorrectly.
Using the wrong variable name for the shape type.
5fill in blank
hard

Fill all three blanks to create a switch expression that returns a message based on the object type and value.

C Sharp (C#)
string message = obj switch {
    [1] when i > 0 => "Positive integer",
    [2] when s.Length == 0 => "Empty string",
    [3] => "Other"
};
Drag options to blanks, or click blank then click option'
Aint i
Bstring s
C_
Ddouble d
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names or types in patterns.
Not using '_' for the default case.