0
0
C Sharp (C#)programming~10 mins

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

Choose your learning style9 modes available
Concept Flow - Property patterns
Start with an object
Check property values
Match pattern?
Execute true
End
Property patterns check if an object's properties match specified values, then decide the flow based on the match.
Execution Sample
C Sharp (C#)
record Person(string Name, int Age);

var person = new Person("Alice", 30);

if (person is { Name: "Alice", Age: 30 })
    Console.WriteLine("Match found");
else
    Console.WriteLine("No match");
This code checks if the person object has Name "Alice" and Age 30, then prints a message accordingly.
Execution Table
StepExpression EvaluatedProperty CheckedValue FoundCondition ResultBranch TakenOutput
1person is { Name: "Alice", Age: 30 }Name"Alice"MatchesContinue
2person is { Name: "Alice", Age: 30 }Age30MatchesContinue
3if conditionN/AN/ATrueTrue branchMatch found
💡 All property checks matched, so the if condition is true and 'Match found' is printed.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
person.Name"Alice""Alice""Alice""Alice"
person.Age30303030
Key Moments - 2 Insights
Why does the pattern check both Name and Age properties?
Because the pattern requires all specified properties to match for the condition to be true, as shown in execution_table rows 1 and 2.
What happens if one property does not match?
The condition becomes false and the else branch runs, as the pattern requires all properties to match (see exit_note).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of person.Name at Step 1?
A"Bob"
B"Alice"
Cnull
D30
💡 Hint
Check the 'Value Found' column at Step 1 in the execution_table.
At which step does the condition become true?
AStep 1
BStep 2
CStep 3
DCondition never becomes true
💡 Hint
Look at the 'Condition Result' and 'Branch Taken' columns in the execution_table.
If person.Age was 25 instead of 30, what would happen?
AThe condition would be false
BThe program would crash
CThe condition would be true
DThe output would be 'Match found'
💡 Hint
Refer to key_moments about property mismatch and exit_note.
Concept Snapshot
Property patterns check if an object's properties match given values.
Syntax: obj is { Prop1: val1, Prop2: val2 }
All specified properties must match for true.
Used in if, switch, or expressions.
Simplifies checking multiple properties at once.
Full Transcript
This example shows how property patterns work in C#. We start with an object 'person' having properties Name and Age. The pattern checks if person.Name equals "Alice" and person.Age equals 30. Each property is checked step-by-step. If all match, the condition is true and the program prints 'Match found'. If any property does not match, the condition is false and the else branch runs. This helps write clear code that checks multiple properties easily.