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

Why pattern matching matters in C Sharp (C#) - Test Your Understanding

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

Complete the code to check if the object is an integer using pattern matching.

C Sharp (C#)
if (obj is [1] number) {
    Console.WriteLine($"Number is {number}");
}
Drag options to blanks, or click blank then click option'
Abool
Bint
Cdouble
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' instead of 'int' for integer check.
2fill in blank
medium

Complete the code to use pattern matching in a switch expression to return a message based on the shape type.

C Sharp (C#)
string message = shape switch {
    Circle c => $"Circle with radius {c.Radius}",
    Rectangle r => $"Rectangle {r.Width}x{r.Height}",
    [1] => "Unknown shape"
};
Drag options to blanks, or click blank then click option'
Adefault
Bnull
C_
Dobject
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'default' keyword which is invalid in this context.
3fill in blank
hard

Fix the error in the pattern matching expression to correctly check if the object is a string with length greater than 5.

C Sharp (C#)
if (obj is string s && s.Length [1] 5) {
    Console.WriteLine("Long string");
}
Drag options to blanks, or click blank then click option'
A>
B<
C==
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' or '==' which do not check for longer strings.
4fill in blank
hard

Fill both blanks to create a pattern matching expression that checks if the object is a Point with X greater than 0 and Y less than 0.

C Sharp (C#)
if (obj is Point [1] && [1].X > 0 && [1].Y [2] 0) {
    Console.WriteLine("Point in quadrant 4");
}
Drag options to blanks, or click blank then click option'
Ap
B>
C<
Dq
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'q' instead of 'p' for the variable name.
Using '>' instead of '<' for Y comparison.
5fill in blank
hard

Fill all three blanks to create a switch expression that returns the area of shapes, using pattern matching with property patterns.

C Sharp (C#)
double area = shape switch {
    Circle [1] => Math.PI * [2].Radius * [3].Radius,
    Rectangle r => r.Width * r.Height,
    _ => 0
};
Drag options to blanks, or click blank then click option'
Ac
Dr
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Using 'r' which is for Rectangle, not Circle.