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