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

Pattern matching in switch 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 match the integer 5 in the switch expression.

C Sharp (C#)
int number = 5;
switch (number)
{
    case [1]:
        Console.WriteLine("Number is five");
        break;
    default:
        Console.WriteLine("Number is not five");
        break;
}
Drag options to blanks, or click blank then click option'
Aint
B"5"
Cnumber
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string "5" instead of the integer 5.
Using the variable name instead of a constant value.
2fill in blank
medium

Complete the code to use pattern matching to check if the object is a string.

C Sharp (C#)
object obj = "hello";
switch (obj)
{
    case [1] s:
        Console.WriteLine($"String with length {s.Length}");
        break;
    default:
        Console.WriteLine("Not a string");
        break;
}
Drag options to blanks, or click blank then click option'
Astring
Bint
Cbool
Ddouble
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong type like int or bool.
Forgetting to include the variable name after the type.
3fill in blank
hard

Fix the error in the switch expression to correctly match a nullable int with value 10.

C Sharp (C#)
int? number = 10;
switch (number)
{
    case [1]:
        Console.WriteLine("Number is ten");
        break;
    default:
        Console.WriteLine("Number is not ten");
        break;
}
Drag options to blanks, or click blank then click option'
Aint n when n == 10
B10
Cint? n when n == 10
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Using just 10 without a pattern.
Using int? n which matches nullable but cannot use when condition properly.
4fill in blank
hard

Fill both blanks to create a switch expression that returns a description for the shape object.

C Sharp (C#)
object shape = new Circle();
string description = shape switch
{
    [1] => "It's a circle",
    [2] => "It's a square",
    _ => "Unknown shape"
};
Drag options to blanks, or click blank then click option'
ACircle c
BSquare s
CTriangle t
DRectangle r
Attempts:
3 left
💡 Hint
Common Mistakes
Using types that don't match the shape object.
Omitting the variable name after the type.
5fill in blank
hard

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

C Sharp (C#)
object input = 42;
string message = input switch
{
    [1] when [2] > 40 => "Large integer",
    [3] => "Not a large integer",
    _ => "Unknown"
};
Drag options to blanks, or click blank then click option'
Aint n
Bn
Cstring s
Ddouble d
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name in the when condition that is not declared in the pattern.
Using the wrong type patterns.