What if your code could instantly know what kind of thing it's dealing with, just like you recognize your favorite toy at a glance?
Why Type patterns in C Sharp (C#)? - Purpose & Use Cases
Imagine you have a box full of different toys, and you want to pick out only the cars. Without a clear way to check each toy's type, you have to open the box, look at each toy carefully, and guess if it's a car or not.
Manually checking each toy's type is slow and tiring. You might make mistakes, like confusing a truck for a car. If you add more toy types, the guessing game becomes even more confusing and error-prone.
Type patterns let you quickly and clearly check what kind of toy you have. You can write simple rules that say, "If this is a car, do this," making your code easier to read and less likely to make mistakes.
if (obj is Car) { var car = (Car)obj; /* use car */ } else if (obj is Truck) { var truck = (Truck)obj; /* use truck */ }
if (obj is Car car) { /* use car */ } else if (obj is Truck truck) { /* use truck */ }
Type patterns make your code smarter and cleaner by letting it recognize and handle different types easily and safely.
Think of a cashier scanning items: type patterns help the system quickly identify if an item is fruit, a drink, or a snack, so it can apply the right price and discount automatically.
Manual type checks are slow and error-prone.
Type patterns simplify and clarify type checking.
They make code safer and easier to maintain.
Practice
if statement like if (obj is string s)?Solution
Step 1: Understand the
Theiskeyword with type patterniskeyword checks if the object is of the specified type.Step 2: Recognize the pattern variable assignment
If the check is true, the object is assigned to the variablesof that type.Final Answer:
Checks ifobjis a string and assigns it tosif true -> Option CQuick Check:
Type pattern = Check and assign [OK]
- Thinking it converts without checking
- Assuming it always returns true
- Expecting an exception on type mismatch
if statement in C#?Solution
Step 1: Recall correct type pattern syntax
The correct syntax isif (variable is Type name).Step 2: Check each option
if (obj is int number) { } matches the correct syntax. Options B, C, and D have incorrect order or keywords.Final Answer:
if (obj is int number) { } -> Option DQuick Check:
Correct syntax = if (obj is Type name) [OK]
if (obj is Type var) [OK]- Swapping type and variable order
- Using 'as' instead of 'is' for pattern
- Placing keywords incorrectly
object obj = 42;
if (obj is int number)
{
Console.WriteLine(number + 10);
}
else
{
Console.WriteLine("Not an int");
}
Solution
Step 1: Check the type of
objobjholds the integer 42, soobj is intis true.Step 2: Calculate the output inside the
The variableifblocknumberis assigned 42, sonumber + 10equals 52, which is printed.Final Answer:
52 -> Option AQuick Check:
Type check true, output = 42 + 10 = 52 [OK]
- Expecting 'Not an int' output
- Confusing type check with cast
- Thinking code throws error
object obj = "hello";
if (obj is int number)
{
Console.WriteLine(number);
}
Solution
Step 1: Analyze the type check condition
objis a string, soobj is int numberis false.Step 2: Understand the effect on output
Since theifcondition is false and noelseblock exists, nothing is printed.Final Answer:
No output becauseobjis not an int -> Option AQuick Check:
False type check = no output [OK]
- Expecting runtime exception
- Thinking else block is mandatory
- Assuming it prints the string
<pre>string Describe(object input)
{
return input switch
{
int i => $"Integer: {i}",
string s => $"String: {s}",
null => "Null value",
_ => "Unknown type"
};
}
What is the result of
Describe(3.14)?Solution
Step 1: Check the switch cases for input 3.14
3.14 is adouble, which does not matchint,string, ornull.Step 2: Identify the default case
The underscore_matches any other type, so it returns "Unknown type".Final Answer:
"Unknown type" -> Option BQuick Check:
Switch default case = "Unknown type" [OK]
- Assuming 3.14 is int or string
- Expecting compilation error
- Ignoring default case
Ready to prove it?
Pass the test and this pattern moves unknown
