Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Type Checking Patterns in C#
π Scenario: Imagine you are building a simple program that processes different shapes. Each shape can be a Circle or a Rectangle. You want to check the type of each shape and calculate its area accordingly.
π― Goal: You will create a list of shapes, add a configuration variable for a minimum area threshold, use type checking patterns to calculate areas only for shapes that meet the threshold, and finally print the areas.
π What You'll Learn
Create a list called shapes containing exactly two objects: a Circle with radius 3 and a Rectangle with width 4 and height 5.
Create a variable called minArea and set it to 10.
Use a foreach loop with type checking patterns to calculate the area of each shape only if it is a Circle or Rectangle and the area is greater than or equal to minArea. Store the results in a dictionary called areas with the shape type name as the key and the area as the value.
Print the areas dictionary.
π‘ Why This Matters
π Real World
Type checking patterns help you write clear and safe code when working with different object types, such as shapes, UI elements, or messages.
πΌ Career
Understanding type checking patterns is important for C# developers to handle polymorphism, improve code readability, and avoid errors when processing mixed data.
Progress0 / 4 steps
1
Create the shapes list
Create a list called shapes containing exactly two objects: a Circle with Radius 3 and a Rectangle with Width 4 and Height 5. Use the provided Circle and Rectangle classes.
C Sharp (C#)
Hint
Use List<object> to hold different shape objects. Add new Circle(3) and new Rectangle(4, 5) inside the list.
2
Add minimum area threshold
Create a variable called minArea and set it to 10.
C Sharp (C#)
Hint
Just create a double variable named minArea and assign it the value 10.
3
Calculate areas using type checking patterns
Use a foreach loop with variables shape to iterate over shapes. Inside the loop, use type checking patterns with is to check if shape is a Circle or Rectangle. Calculate the area for each shape: for Circle, area = Ο x radiusΒ²; for Rectangle, area = width x height. Only add the shape type name and area to a dictionary called areas if the area is greater than or equal to minArea. Use Math.PI for Ο.
C Sharp (C#)
Hint
Use foreach (object shape in shapes). Inside, use if (shape is Circle c) and else if (shape is Rectangle r). Calculate area accordingly and add to areas dictionary only if area ≥ minArea.
4
Print the areas dictionary
Use a foreach loop with variables key and value to iterate over areas. Print each shape type and its area in the format: "{key}: {value:F2}" where {value:F2} formats the area to 2 decimal places.
C Sharp (C#)
Hint
Use foreach (var (key, value) in areas) and Console.WriteLine($"{key}: {value:F2}") to print each shape and its area with two decimals.
Practice
(1/5)
1. What does the C# pattern if (obj is string s) do?
easy
A. Checks if obj is null
B. Converts obj to string without checking
C. Checks if obj is a string and assigns it to s if true
D. Throws an exception if obj is not a string
Solution
Step 1: Understand the is pattern
The is keyword checks if an object is of a certain type.
Step 2: Assign variable if type matches
If obj is a string, it assigns the value to s for use inside the block.
Final Answer:
Checks if obj is a string and assigns it to s if true -> Option C
Quick Check:
is Type var checks type and assigns [OK]
Hint: Remember: is Type var checks and assigns together [OK]
Common Mistakes:
Thinking it converts without checking
Assuming it checks for null only
Believing it throws exceptions automatically
2. Which of the following is the correct syntax to check if obj is an int and assign it to number?
easy
A. if (obj is int number) { }
B. if (obj as int number) { }
C. if (obj == int number) { }
D. if (obj instanceof int number) { }
Solution
Step 1: Identify correct C# type pattern syntax
The correct syntax uses is Type variable to check and assign.
Step 2: Compare options
if (obj is int number) { } uses is int number, which is valid. Others use invalid keywords or syntax.
Final Answer:
if (obj is int number) { } -> Option A
Quick Check:
is Type var syntax is correct [OK]
Hint: Use is Type var for type check and assignment [OK]
Common Mistakes:
Using 'as' instead of 'is' for type checking
Using '==' to compare types
Using JavaScript or Java keywords like 'instanceof'
3. What is the output of this code?
object obj = 42;
if (obj is int n)
{
Console.WriteLine(n + 10);
}
else
{
Console.WriteLine("Not an int");
}
medium
A. Not an int
B. 52
C. 42
D. Compilation error
Solution
Step 1: Check the type of obj
obj holds the integer 42, so obj is int n is true and assigns 42 to n.
Step 2: Calculate the output inside the if block
It prints n + 10 which is 42 + 10 = 52.
Final Answer:
52 -> Option B
Quick Check:
Type check passes, output is 42 + 10 = 52 [OK]
Hint: If type matches, variable holds value for use [OK]
Common Mistakes:
Printing the original obj instead of n + 10
Choosing else output wrongly
Thinking it causes a compile error
4. Identify the error in this code snippet:
object obj = "hello";
if (obj is int number)
{
Console.WriteLine(number);
}
medium
A. No error, code runs and prints number
B. Runtime exception thrown
C. Syntax error in the if statement
D. The variable 'number' is not assigned because obj is not int
Solution
Step 1: Analyze the type check
obj is a string, so obj is int number is false and number is not assigned.
Step 2: Understand the effect on code execution
The if block is skipped, so nothing prints. No error or exception occurs.
Final Answer:
The variable 'number' is not assigned because obj is not int -> Option D
Quick Check:
Type check false means variable not assigned [OK]
Hint: If type check fails, variable is not assigned [OK]
Common Mistakes:
Thinking it causes syntax error
Expecting runtime exception
Assuming variable is assigned anyway
5. Given a list of objects List<object> items = new() { 1, "two", 3, null, 4.5 };, which code snippet correctly sums only the integer values using type checking patterns?
hard
A. int sum = 0;
foreach (var item in items)
{
if (item is int n) sum += n;
}
Console.WriteLine(sum);
B. int sum = 0;
foreach (int n in items)
{
sum += n;
}
Console.WriteLine(sum);
C. int sum = 0;
foreach (var item in items)
{
if (item is double d) sum += (int)d;
}
Console.WriteLine(sum);
D. int sum = 0;
foreach (var item in items)
{
sum += (int)item;
}
Console.WriteLine(sum);
Solution
Step 1: Understand the list contents
The list has integers, a string, null, and a double. We want to sum only integers.
Step 2: Check each option for correct type filtering
int sum = 0;
foreach (var item in items)
{
if (item is int n) sum += n;
}
Console.WriteLine(sum); uses if (item is int n) to add only integers. int sum = 0;
foreach (int n in items)
{
sum += n;
}
Console.WriteLine(sum); tries to cast all items to int in foreach, causing error. int sum = 0;
foreach (var item in items)
{
if (item is double d) sum += (int)d;
}
Console.WriteLine(sum); sums doubles cast to int, which is incorrect. int sum = 0;
foreach (var item in items)
{
sum += (int)item;
}
Console.WriteLine(sum); casts all items to int without checking, causing runtime errors.
Final Answer:
int sum = 0;
foreach (var item in items)
{
if (item is int n) sum += n;
}
Console.WriteLine(sum); -> Option A
Quick Check:
Use is int var to filter integers safely [OK]
Hint: Use if (item is int n) to sum integers safely [OK]