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

Value equality in records in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Value equality in records
Create record instance A
↓
Create record instance B
↓
Compare A and B
↓
Return true
This flow shows how two record instances are created and compared by their values, returning true if all properties match.
Execution Sample
C Sharp (C#)
public record Person(string Name, int Age);

var p1 = new Person("Alice", 30);
var p2 = new Person("Alice", 30);

bool areEqual = p1 == p2;
Console.WriteLine(areEqual);
This code creates two Person records with the same data and compares them for value equality, printing the result.
Execution Table
StepActionEvaluationResult
1Create p1 with Name="Alice", Age=30p1 = Person(Name="Alice", Age=30)p1 created
2Create p2 with Name="Alice", Age=30p2 = Person(Name="Alice", Age=30)p2 created
3Compare p1 == p2Compare all properties: Name and AgeTrue (values equal)
4Print areEqualOutput value of areEqualTrue
💡 Comparison ends after checking all properties are equal, so result is True.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
p1nullPerson(Name="Alice", Age=30)Person(Name="Alice", Age=30)Person(Name="Alice", Age=30)Person(Name="Alice", Age=30)
p2nullnullPerson(Name="Alice", Age=30)Person(Name="Alice", Age=30)Person(Name="Alice", Age=30)
areEqualundefinedundefinedundefinedTrueTrue
Key Moments - 2 Insights
Why does p1 == p2 return true even though they are different objects?
Because records in C# compare their contents (values of properties) for equality, not their memory addresses. See execution_table step 3 where all properties are compared.
What if one property differs between p1 and p2?
Then the comparison returns false because value equality requires all properties to match exactly. This is shown in execution_table step 3 where all properties must be equal.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the result of comparing p1 and p2?
AThrows error
BFalse
CTrue
DNull
💡 Hint
Check the 'Result' column in step 3 of execution_table.
According to variable_tracker, what is the value of areEqual after step 3?
AFalse
BTrue
Cnull
Dundefined
💡 Hint
Look at the 'areEqual' row under 'After Step 3' in variable_tracker.
If p2 was created with Age=31 instead of 30, what would be the comparison result?
AFalse
BTrue
CThrows exception
DComparison skipped
💡 Hint
Value equality requires all properties to match exactly, see key_moments explanation.
Concept Snapshot
C# records compare by value, not reference.
Use '==' to check if all properties are equal.
Records auto-generate equality methods.
Different objects with same data are equal.
If any property differs, equality is false.
Full Transcript
This example shows how C# records compare two instances by their values. Two Person records with the same Name and Age are created. When compared with '==', the result is true because records check if all properties match. The variable 'areEqual' stores this result and prints true. This demonstrates value equality in records, meaning objects with identical data are considered equal even if they are different instances.

Practice

(1/5)
1. What is the main feature of record types in C# regarding equality?
easy
A. They require manual implementation of equality methods.
B. They compare objects by their memory address only.
C. They cannot be compared for equality.
D. They compare objects by their data automatically.

Solution

  1. Step 1: Understand record equality behavior

    Records in C# automatically implement value equality, meaning two records with the same data are considered equal.
  2. Step 2: Contrast with normal classes

    Normal classes compare by reference (memory address) unless equality is overridden manually.
  3. Final Answer:

    They compare objects by their data automatically. -> Option D
  4. Quick Check:

    Record equality = value-based [OK]
Hint: Records compare data, not references, by default [OK]
Common Mistakes:
  • Thinking records compare by reference like classes
  • Assuming manual equality override is needed
  • Believing records cannot be compared
2. Which of the following is the correct syntax to declare a positional record in C#?
easy
A. class Person { public string Name; }
B. record Person { string Name; }
C. record Person(string Name);
D. struct Person(string Name);

Solution

  1. Step 1: Identify record declaration syntax

    The concise syntax for a record with a positional parameter is record Person(string Name);.
  2. Step 2: Check other options

    class Person { public string Name; } is a class, not a record. struct Person(string Name); is a struct, not a record. record Person { string Name; } is invalid because positional parameters require parentheses.
  3. Final Answer:

    record Person(string Name); -> Option C
  4. Quick Check:

    Record syntax = record Name(params) [OK]
Hint: Use 'record Name(params);' for simple record declaration [OK]
Common Mistakes:
  • Using class instead of record
  • Missing parentheses for positional parameters
  • Confusing struct with record
3. What will be the output of the following code?
record Point(int X, int Y);

var p1 = new Point(3, 4);
var p2 = new Point(3, 4);
Console.WriteLine(p1 == p2);
medium
A. True
B. Compilation error
C. False
D. Runtime exception

Solution

  1. Step 1: Understand record equality operator

    Records override the equality operator to compare values, so p1 == p2 compares the data inside the records.
  2. Step 2: Compare values of p1 and p2

    Both have X=3 and Y=4, so they are equal and the output is True.
  3. Final Answer:

    True -> Option A
  4. Quick Check:

    Records with same data == True [OK]
Hint: Records compare data with == operator automatically [OK]
Common Mistakes:
  • Assuming == compares references for records
  • Expecting compilation error due to operator
  • Thinking output is False because objects differ
4. Identify the error in this code snippet:
record Person(string Name);

var p1 = new Person("Alice");
var p2 = new Person("Alice");

if (p1.Equals(p2))
    Console.WriteLine("Equal");
else
    Console.WriteLine("Not Equal");

p1.Name = "Bob";
medium
A. Records cannot use Equals method.
B. Cannot assign to 'Name' because it is init-only.
C. Missing semicolon after record declaration.
D. p1 and p2 are different objects, so Equals returns false.

Solution

  1. Step 1: Check mutability of record properties

    By default, positional record properties are immutable (init-only), so p1.Name = "Bob"; causes a compile error.
  2. Step 2: Verify other statements

    Using Equals is valid and compares values correctly. The semicolon after record declaration is present. Equals returns true because data matches.
  3. Final Answer:

    Cannot assign to 'Name' because it is init-only. -> Option B
  4. Quick Check:

    Record properties are immutable by default [OK]
Hint: Record properties are init-only; cannot assign after creation [OK]
Common Mistakes:
  • Trying to modify record properties after creation
  • Thinking Equals compares references
  • Ignoring immutability of positional properties
5. Given two records record Product(int Id, string Name);, how can you create a new record from an existing one but with a different Name while keeping Id the same?
hard
A. Use the 'with' expression: var p2 = p1 with { Name = "NewName" };
B. Create a new record manually: var p2 = new Product(p1.Name, "NewName");
C. Assign directly: p1.Name = "NewName";
D. Use a method to clone and change: var p2 = p1.Clone("NewName");

Solution

  1. Step 1: Understand the 'with' expression for records

    The 'with' expression creates a copy of a record with specified properties changed.
  2. Step 2: Compare options

    Use the 'with' expression: var p2 = p1 with { Name = "NewName" }; uses 'with' correctly. Create a new record manually: var p2 = new Product(p1.Name, "NewName"); fails to compile because Id expects int but p1.Name is string. Assign directly: p1.Name = "NewName"; is invalid because record properties are immutable. Use a method to clone and change: var p2 = p1.Clone("NewName"); is invalid as no Clone method exists by default.
  3. Final Answer:

    Use the 'with' expression: var p2 = p1 with { Name = "NewName" }; -> Option A
  4. Quick Check:

    'with' creates modified record copies [OK]
Hint: Use 'with' to copy and change record properties easily [OK]
Common Mistakes:
  • Trying to assign directly to immutable properties
  • Not using 'with' for copying records
  • Assuming a Clone method exists by default
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