why the Clist.Contains(customer) is not getting true in that case ?
why the Clist.Contains(customer) is not getting true while the new object that i created is already on the list dose that means that i have to override the Equals method in the customer class
i have tried to override the Equals() method in the customer class but, what was intersting is that it works
20 Replies
Yes you need to implement value semantics (Equals, and likely you want GetHashCode too)
The easy way is to just use a record instead of a class and the compiler will implement all of that for you.
i did not get this can you explain
public record Customer(int Id, string Name);
Classes by default use reference semantics meaning comparing them for equality just checks if the variables point to the same instance in memory.
So if you want to compare them based on the data they contain, you need to implement value semantics:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type
How to define value equality for a class or struct - C#
Learn how to define value equality for a class or struct. See code examples and view available resources.
Yes, that's the way to fix it.
record is a type that are different than class
Record is a type with value equality built-in
C# has two types of objects: value types and reference types
Value types are compared by their... values.
Reference types, by their references
yes i understand this that`s why i override the Equals up there , but record can be a struct or a class this means that it can ethier a value type or a refrence type
Yes, there are
record
s and record struct
s
In either case, comparison will be by valuehem but if it is a record only then it will be refrence type
A reference type with value semantics
Angius
REPL Result: Success
Result: bool
Compile: 330.892ms | Execution: 66.034ms | React with ❌ to remove this embed.
Here's what a record compiles down to
yes , also i have another question records can be used instead of the class in case i am dealing with databases