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

Value equality in records in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Record Equality Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of comparing two records with same values
What is the output of this C# code snippet?
C Sharp (C#)
public record Person(string Name, int Age);

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

Console.WriteLine(p1 == p2);
ATrue
BFalse
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
Records in C# have built-in value equality.
Predict Output
intermediate
2:00remaining
Output of comparing record and class with same properties
What is the output of this C# code snippet?
C Sharp (C#)
public record PersonRecord(string Name, int Age);
public class PersonClass { public string Name { get; init; } public int Age { get; init; } }

var r = new PersonRecord("Bob", 25);
var c = new PersonClass { Name = "Bob", Age = 25 };

Console.WriteLine(r.Equals(c));
ATrue
BRuntime exception
CCompilation error
DFalse
Attempts:
2 left
💡 Hint
Records and classes have different equality implementations.
🔧 Debug
advanced
2:30remaining
Why does this record equality fail?
Consider this code snippet. Why does the equality check return false? public record Point(int X, int Y); var p1 = new Point(1, 2); var p2 = new Point(1, 3); Console.WriteLine(p1 == p2);
C Sharp (C#)
public record Point(int X, int Y);

var p1 = new Point(1, 2);
var p2 = new Point(1, 3);

Console.WriteLine(p1 == p2);
ABecause the Y values differ, so the records are not equal
BBecause records cannot be compared with == operator
CBecause the X values differ, so the records are not equal
DBecause the record does not override Equals method
Attempts:
2 left
💡 Hint
Check the values of both records' properties.
📝 Syntax
advanced
2:00remaining
Which record declaration is invalid?
Which of the following C# record declarations will cause a compilation error?
Apublic record Car(string Make, string Model);
Bpublic record Car { public string Make { get; init; } public string Model { get; init; } }
Cpublic record Car(string Make, string Model) { public int Year; }
Dpublic record Car(string Make, string Model) { public int Year { get; set; } }
Attempts:
2 left
💡 Hint
Check if the record has invalid field declarations.
🚀 Application
expert
2:30remaining
How many items in the HashSet after adding records?
Given this code, how many items will the HashSet contain after execution?
C Sharp (C#)
public record Employee(string Id, string Name);

var set = new HashSet<Employee>();
set.Add(new Employee("E01", "John"));
set.Add(new Employee("E01", "John"));
set.Add(new Employee("E02", "Jane"));
set.Add(new Employee("E01", "John"));

Console.WriteLine(set.Count);
A1
B2
C3
D4
Attempts:
2 left
💡 Hint
HashSet uses equality to avoid duplicates.