Add support to configure culture/casing of string properties on record types #80914
-
|
I ran into the common surprise with records: the compiler-generated equality for record members uses the default equality for each member type, so string members are compared case‑sensitively. That’s the right default in many cases, but it’s awkward when your domain expects case-insensitive string equality (e.g. identifiers, file extensions, user names, tags, etc.). public record Person(string Name);
Assert.Equals(new Person("John"), new Person("john")); // assert failsThere’s already a clear report/discussion on csharplang about this: dotnet/csharplang#6994 — Seems like the OP never took the time to move the discussion here, so I'm doing it.
So, one could do this: [StringComparison(StringComparison.InvariantCultureIgnoreCase)]
public record Person(string Name);
Assert.Equals(new Person("John"), new Person("john")); // assert passWould love to hear whether the Roslyn maintainers are open to this approach (or whether there’s another low-friction path you’d prefer). |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
|
You can already accomplish this today. Just write a source generator that spits out an appropriate .Equals and GetHashCode based on whatever attributes you care about. The language or Roslyn doesn't need to do anything here as the extensibility point is already available. |
Beta Was this translation helpful? Give feedback.
-
|
What I am seeing folks sometimes do in practice is to define a wrapper type, which performs the comparison on the underlying type in the desired way, and use that as the member type in the record instead. For example |
Beta Was this translation helpful? Give feedback.
You can already accomplish this today. Just write a source generator that spits out an appropriate .Equals and GetHashCode based on whatever attributes you care about. The language or Roslyn doesn't need to do anything here as the extensibility point is already available.