How to make Record case insensitive. #6994
-
I have some code such as following Person person1 = new(FirstName: "Nancy", LastName: "davolio"); //lowercase
Person person2 = new(FirstName: "Nancy", LastName: "Davolio");
Person person3 = new(FirstName: "Nancy", LastName: "Davolio");
Console.WriteLine(value: person1 == person2); // output:expect True but actually False ----
Console.WriteLine(value: person3 == person2); // output: True
Console.WriteLine(value: ReferenceEquals(objA: person1, objB: person2)); // output: False
Console.WriteLine(value: ReferenceEquals(objA: person3, objB: person2)); // output: False
Console.WriteLine(value: "Hello, World!");
public record Person(string FirstName, string LastName); Output is
Meaning |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 8 replies
-
Override .Equals in your record to implement whatever equality semantics you want. |
Beta Was this translation helpful? Give feedback.
-
I want to use the class person as key for a dictionary class such as public class Portfolio{...}
public record Person (string FirstName, string LastName);
public class PersonProfolioDict : Dictionary<Person, Portfolio> {...}; So I believe the function public record Person(string FirstName, string LastName)
{
public virtual bool Equals(Person? p)
{
if (ReferenceEquals(p, null)) return false;
if (ReferenceEquals(p, this)) return true;
return
string.Equals(FirstName, p.FirstName, StringComparison.InvariantCultureIgnoreCase) &&
string.Equals(LastName, p.LastName, StringComparison.InvariantCultureIgnoreCase)
;
}
public override int GetHashCode()
{
return HashCode.Combine(FirstName.ToUpperInvariant(), LastName.ToUpperInvariant());
//for Net <6.0
//return FirstName.ToUpperInvariant( ).GetHashCode() ^ LastName.ToUpperInvariant().GetHashCode();
}
} Is it correct? public record Person
(
[StringComparison(StringComparison.InvariantCultureIgnoreCase)]
string FirstName,
[StringComparison(StringComparison.InvariantCultureIgnoreCase)]
string LastName
); Thank you all for your attention! |
Beta Was this translation helpful? Give feedback.
-
Another alternative is to do something like this: public sealed record Person(Name FirstName, Name LastName);
public readonly struct Name : IEquatable<Name>
{
public readonly string _value;
public Name(string value)
=> _value = value;
public bool Equals(Name other)
{
return string.Equals(
_value,
other._value,
StringComparison.InvariantCultureIgnoreCase);
}
public override int GetHashCode()
=> StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value);
public static implicit operator string(Name name) => name._value;
public static implicit operator Name(string value) => new Name(value);
} |
Beta Was this translation helpful? Give feedback.
Override .Equals in your record to implement whatever equality semantics you want.