Pattern Matching — The Building Inspector
20 XPMedium
Ctrl+Enter RunCtrl+S Save
🔎 The Inspector's Magnifying Glass
A new challenge arrives, Architect. The city's Building Inspector needs a smart classification system. Buildings come in all shapes and forms — commercial towers, residential complexes, public parks, industrial warehouses. Each type has different rules, permits, and inspection priorities.
You could chain endless if/else blocks… but C# offers something far more powerful: Pattern Matching. It's like giving the inspector X-ray vision — the ability to look at an object, identify its type, examine its properties, and make decisions, all in one elegant expression.
🧬 The is Keyword — Type Checking
The is keyword checks whether an object is of a specific type. In C# 7+, it can also declare a variable in the same step:
object building = "Commercial";
// Classic type check
if (building is string)
{
Console.WriteLine("It's a string!");
}
// C# 7+: Type check AND cast in one step
if (building is string buildingType)
{
Console.WriteLine($"Building type: {buildingType}");
// buildingType is now a string variable — no manual cast needed!
}
🔢 Constant & Relational Patterns
Pattern matching goes beyond types. You can match against constants and even use relational operators (C# 9+):
C# 9 introduced pattern combinators that read like English:
int sqft = 15000;
// Combine patterns with 'and', 'or', 'not'
string category = sqft switch
{
>= 10000 and < 50000 => "Large",
>= 5000 and < 10000 => "Medium",
> 0 and < 5000 => "Small",
0 => "Empty",
_ => "Invalid"
};
// 'not' pattern
if (sqft is not 0)
{
Console.WriteLine("This lot has area");
}
🛡️ The when Clause — Extra Guard Conditions
Sometimes the pattern alone isn't enough. The when clause adds an extra condition — like the inspector double-checking credentials:
object item = 15000;
switch (item)
{
case int area when area >= 10000:
Console.WriteLine($"Large building: {area} sqft");
break;
case int area when area >= 5000:
Console.WriteLine($"Medium building: {area} sqft");
break;
case int area:
Console.WriteLine($"Small building: {area} sqft");
break;
case string name:
Console.WriteLine($"Building name: {name}");
break;
default:
Console.WriteLine("Unknown item");
break;
}
✨ Switch Expressions with Patterns — The Full Power
Combine switch expressions with pattern matching for maximum elegance:
object building = (Type: "Commercial", Sqft: 15000);
// Using tuples with switch expression
var info = ("Commercial", 15000);
string result = info switch
{
("Commercial", >= 10000) => "Large Commercial — Priority Inspection",
("Commercial", _) => "Small Commercial — Standard Inspection",
("Residential", >= 5000) => "Large Residential — Scheduled Inspection",
("Residential", _) => "Small Residential — Self-Certified",
_ => "Unknown — Manual Review"
};
Console.WriteLine(result);
🆚 is vs as
is — Returns bool. Checks type. In C# 7+, can declare a typed variable. Safe and expressive.
as — Attempts a cast and returns null if it fails (reference types only). Use when you want the casted value and can handle null.
Prefer is with pattern variable for most scenarios — it's safer, more readable, and works with value types too.
📈 Pattern Matching Evolution
C# 7: Type patterns, constant patterns, when clause in switch
The Inspector needs a classification engine. Given a building type and area, your program must determine the category, area size, whether a permit is required, and the inspection priority. Time to put those pattern matching skills to work!
📋 Instructions
**The Building Inspector's Classification Engine**
You have two variables:
- `string buildingType = "Commercial";`
- `int sqft = 15000;`
Write a program that:
1. **Print the building type**: `"Type: Commercial"`
2. **Classify the area** using a switch expression with relational patterns:
- `>= 10000` → `"Large"`
- `>= 5000` → `"Medium"`
- `> 0` → `"Small"`
- Otherwise → `"Unknown"`
- Print: `"Area: Large"`
3. **Determine if a permit is required** using pattern matching with `is`:
- If `buildingType` is `"Commercial"` or `"Industrial"` → `"Yes"`
- Otherwise → `"No"`
- Print: `"Permit Required: Yes"`
4. **Set inspection priority** using a tuple pattern in a switch expression on `(buildingType, sqft)`:
- `("Commercial", >= 10000)` → `"Priority"`
- `("Commercial", _)` → `"Standard"`
- `("Residential", >= 10000)` → `"Standard"`
- `("Residential", _)` → `"Low"`
- Everything else → `"Review"`
- Print: `"Inspection: Priority"`
Output must match **exactly**.
For Step 2: string size = sqft switch { >= 10000 => "Large", >= 5000 => "Medium", > 0 => "Small", _ => "Unknown" }; For Step 3: string permit = (buildingType is "Commercial" or "Industrial") ? "Yes" : "No"; For Step 4: use (buildingType, sqft) switch { ("Commercial", >= 10000) => "Priority", ... };