Type checking patterns help you check what kind of data you have and use it safely in your code.
Type checking patterns in C Sharp (C#)
Start learning this pattern below
Jump into concepts and practice - no test required
if (variable is TypeName name) { // use 'name' here }
The is keyword checks the type and assigns the variable if it matches.
This pattern helps avoid extra casting and makes code safer and cleaner.
obj is a string, then uses it as s.object obj = "hello"; if (obj is string s) { Console.WriteLine(s.ToUpper()); }
obj is an int, then adds 10 to it.object obj = 123; if (obj is int number) { Console.WriteLine(number + 10); }
is null.object obj = null; if (obj is null) { Console.WriteLine("Object is null"); }
This program checks each item in an array. It prints the uppercase string if it's a string, adds 1 if it's an integer, notes if it's null, and says "Other type detected" for anything else.
using System; class Program { static void Main() { object[] items = { "apple", 42, 3.14, null }; foreach (var item in items) { if (item is string text) { Console.WriteLine($"String: {text.ToUpper()}"); } else if (item is int number) { Console.WriteLine($"Integer: {number + 1}"); } else if (item is null) { Console.WriteLine("Null value found"); } else { Console.WriteLine("Other type detected"); } } } }
Type checking patterns reduce the need for manual casting and make code safer.
They work well with switch statements for cleaner multi-type checks.
Type checking patterns let you test and use variables by their type easily.
They help avoid errors by ensuring you only use data in the right way.
Using is TypeName name is a simple and clear way to check types and get values.
Practice
if (obj is string s) do?Solution
Step 1: Understand the
Theispatterniskeyword checks if an object is of a certain type.Step 2: Assign variable if type matches
Ifobjis a string, it assigns the value tosfor use inside the block.Final Answer:
Checks if obj is a string and assigns it to s if true -> Option CQuick Check:
is Type varchecks type and assigns [OK]
is Type var checks and assigns together [OK]- Thinking it converts without checking
- Assuming it checks for null only
- Believing it throws exceptions automatically
obj is an int and assign it to number?Solution
Step 1: Identify correct C# type pattern syntax
The correct syntax usesis Type variableto check and assign.Step 2: Compare options
if (obj is int number) { } usesis int number, which is valid. Others use invalid keywords or syntax.Final Answer:
if (obj is int number) { } -> Option AQuick Check:
is Type varsyntax is correct [OK]
is Type var for type check and assignment [OK]- Using 'as' instead of 'is' for type checking
- Using '==' to compare types
- Using JavaScript or Java keywords like 'instanceof'
object obj = 42;
if (obj is int n)
{
Console.WriteLine(n + 10);
}
else
{
Console.WriteLine("Not an int");
}Solution
Step 1: Check the type of obj
obj holds the integer 42, soobj is int nis true and assigns 42 to n.Step 2: Calculate the output inside the if block
It printsn + 10which is 42 + 10 = 52.Final Answer:
52 -> Option BQuick Check:
Type check passes, output is 42 + 10 = 52 [OK]
- Printing the original obj instead of n + 10
- Choosing else output wrongly
- Thinking it causes a compile error
object obj = "hello";
if (obj is int number)
{
Console.WriteLine(number);
}Solution
Step 1: Analyze the type check
obj is a string, soobj is int numberis 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 DQuick Check:
Type check false means variable not assigned [OK]
- Thinking it causes syntax error
- Expecting runtime exception
- Assuming variable is assigned anyway
List<object> items = new() { 1, "two", 3, null, 4.5 };, which code snippet correctly sums only the integer values using type checking patterns?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); usesif (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 AQuick Check:
Useis int varto filter integers safely [OK]
if (item is int n) to sum integers safely [OK]- Casting without checking causing exceptions
- Summing wrong types like double or string
- Assuming foreach int works on object list
