Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Type patterns in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Type patterns
Start with object variable
↓
Check type with pattern
↓
Cast and use
↓
End
The program checks if an object matches a type pattern, then uses it if yes, otherwise skips or does other actions.
Execution Sample
C Sharp (C#)
object obj = 42;
if (obj is int number)
{
    Console.WriteLine(number + 10);
}
Checks if obj is an int, assigns it to number, then prints number plus 10.
Execution Table
StepActionEvaluationResult
1Assign obj = 42obj holds 42 (int)obj = 42
2Check if obj is intobj is int? Truenumber = 42
3Execute inside ifPrint number + 10Output: 52
4EndNo more codeProgram ends
💡 After printing 52, program ends as no more code follows.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
objnull42 (int)42 (int)42 (int)
numberundefinedundefined4242
Key Moments - 2 Insights
Why does 'number' get a value only after the type check?
Because 'number' is declared inside the 'if' condition using the type pattern, it only gets assigned if 'obj is int' is true, as shown in execution_table step 2.
What happens if obj is not an int?
The 'if' block is skipped because the type pattern fails, so 'number' is never assigned and the code inside the block does not run, as implied by the 'No' branch in concept_flow.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the value of 'number'?
Aundefined
Bnull
C42
D10
💡 Hint
Check the 'Result' column at step 2 in execution_table where 'number = 42' is assigned.
At which step does the program print output?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' and 'Result' columns in execution_table for the printing action.
If obj was a string instead of int, what would happen?
AThe if block is skipped, no output printed
BCompilation error
CThe if block runs and prints the string plus 10
DThe program crashes
💡 Hint
Refer to concept_flow where the 'No' branch skips the block if type pattern fails.
Concept Snapshot
Type patterns check if an object matches a type.
Syntax: if (obj is Type varName) { use varName }
If true, varName holds the casted value.
If false, block is skipped.
Useful for safe type checks and casts.
Full Transcript
This example shows how C# uses type patterns to check an object's type safely. We start with an object variable 'obj' assigned the value 42, which is an int. The 'if' statement uses 'obj is int number' to check if obj is an int. If true, it assigns obj to a new variable 'number' of type int. Inside the 'if' block, we print number plus 10, resulting in 52. If obj was not an int, the block would be skipped and no output printed. This pattern helps avoid manual casting and errors by combining type check and assignment in one step.

Practice

(1/5)
1. What does a type pattern in C# do when used in an if statement like if (obj is string s)?
easy
A. Always returns true regardless of obj type
B. Converts obj to a 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

  1. Step 1: Understand the is keyword with type pattern

    The is keyword checks if the object is of the specified type.
  2. Step 2: Recognize the pattern variable assignment

    If the check is true, the object is assigned to the variable s of that type.
  3. Final Answer:

    Checks if obj is a string and assigns it to s if true -> Option C
  4. Quick Check:

    Type pattern = Check and assign [OK]
Hint: Type pattern checks type and assigns in one step [OK]
Common Mistakes:
  • Thinking it converts without checking
  • Assuming it always returns true
  • Expecting an exception on type mismatch
2. Which of the following is the correct syntax for using a type pattern in an if statement in C#?
easy
A. if (obj as int number) { }
B. if (int obj is number) { }
C. if (obj int is number) { }
D. if (obj is int number) { }

Solution

  1. Step 1: Recall correct type pattern syntax

    The correct syntax is if (variable is Type name).
  2. Step 2: Check each option

    if (obj is int number) { } matches the correct syntax. Options B, C, and D have incorrect order or keywords.
  3. Final Answer:

    if (obj is int number) { } -> Option D
  4. Quick Check:

    Correct syntax = if (obj is Type name) [OK]
Hint: Remember: if (obj is Type var) [OK]
Common Mistakes:
  • Swapping type and variable order
  • Using 'as' instead of 'is' for pattern
  • Placing keywords incorrectly
3. What will be the output of this C# code?
object obj = 42;
if (obj is int number)
{
Console.WriteLine(number + 10);
}
else
{
Console.WriteLine("Not an int");
}
medium
A. 52
B. Not an int
C. Compilation error
D. Runtime exception

Solution

  1. Step 1: Check the type of obj

    obj holds the integer 42, so obj is int is true.
  2. Step 2: Calculate the output inside the if block

    The variable number is assigned 42, so number + 10 equals 52, which is printed.
  3. Final Answer:

    52 -> Option A
  4. Quick Check:

    Type check true, output = 42 + 10 = 52 [OK]
Hint: If type matches, variable holds value for use [OK]
Common Mistakes:
  • Expecting 'Not an int' output
  • Confusing type check with cast
  • Thinking code throws error
4. Identify the error in this code snippet using type patterns:
object obj = "hello";
if (obj is int number)
{
Console.WriteLine(number);
}
medium
A. No output because obj is not an int
B. Compilation error due to missing else block
C. No error, code runs and prints 'hello'
D. Runtime exception when casting string to int

Solution

  1. Step 1: Analyze the type check condition

    obj is a string, so obj is int number is false.
  2. Step 2: Understand the effect on output

    Since the if condition is false and no else block exists, nothing is printed.
  3. Final Answer:

    No output because obj is not an int -> Option A
  4. Quick Check:

    False type check = no output [OK]
Hint: False type check skips block, no output [OK]
Common Mistakes:
  • Expecting runtime exception
  • Thinking else block is mandatory
  • Assuming it prints the string
5. Given this method using type patterns, what will it return?
<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)?
hard
A. "Integer: 3"
B. "Unknown type"
C. "String: 3.14"
D. Compilation error

Solution

  1. Step 1: Check the switch cases for input 3.14

    3.14 is a double, which does not match int, string, or null.
  2. Step 2: Identify the default case

    The underscore _ matches any other type, so it returns "Unknown type".
  3. Final Answer:

    "Unknown type" -> Option B
  4. Quick Check:

    Switch default case = "Unknown type" [OK]
Hint: Switch default (_) handles unmatched types [OK]
Common Mistakes:
  • Assuming 3.14 is int or string
  • Expecting compilation error
  • Ignoring default case
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard