C
C#2y ago
Vir Godem

How do collections implement Remove and Contains?

In particular, in the case of records. Do they look for exact references, or do they apply the record equality test as I'd expect them to? Let's say I've got a simple record like:
record S(int X, string Y);
record S(int X, string Y);
And I've got a collection of S, such as a HashSet. Will the HashSet test the values of X and Y and return true if it finds that the HashSet contains such an element? Or will it need the exact reference to S? That is, would the following be enough to find a reference containing an S instance with X = 5 and Y = "42"?
return HashSet.Contains(new S(5, "42"));
return HashSet.Contains(new S(5, "42"));
4 Replies
Angius
Angius2y ago
$tias?
MODiX
MODiX2y ago
Angius#1586
REPL Result: Success
record S(int X, string Y);

var l = new List<S> {
new (69, "nice"),
new (420, "blaze it"),
new (900, "unga")
};

l.Remove(new S(900, "unga"));

(
l.Contains(new S(69, "nice")),
l
)
record S(int X, string Y);

var l = new List<S> {
new (69, "nice"),
new (420, "blaze it"),
new (900, "unga")
};

l.Remove(new S(900, "unga"));

(
l.Contains(new S(69, "nice")),
l
)
Result: ValueTuple<bool, List<S>>
{
"item1": true,
"item2": [
{
"x": 69,
"y": "nice"
},
{
"x": 420,
"y": "blaze it"
}
]
}
{
"item1": true,
"item2": [
{
"x": 69,
"y": "nice"
},
{
"x": 420,
"y": "blaze it"
}
]
}
Compile: 684.494ms | Execution: 91.355ms | React with ❌ to remove this embed.
Vir Godem
Vir GodemOP2y ago
Alright lol.
Want results from more Discord servers?
Add your server