✅ Is there a way you can check if an object’s equality operator will compare by reference?

I want to implement a data validation attribute like [UniqueValues] for ASP.NET model binding which will basically just call .Distinct() and check the count against the original list. This however won’t work with plain classes, only value types, records, or classes that implement IEquatable. Is there a way I can check an object instance to see if it will be compared by reference, and if so throw an exception?
5 Replies
dreadfullydistinct
To clarify I want the attribute to operate on a list
jcotton42
jcotton424mo ago
I would just require IEquatable<T> Pretty sure records have that interface
dreadfullydistinct
Hmm I guess then you have to have the attribute be [UniqueValues<T>] public List<T> Property
Angius
Angius4mo ago
Or just check if (prop is IEquatable<>) Ah, does pattern matching work with open generics, that's the question...
dreadfullydistinct
I don’t think so based on a quick sharplab I wonder if you could use reflection to check that it implements that interface Open generics might work there Went with IEquatable<TElement> because we wanted to pattern match the input is an enumerable to call Distinct, and it turns out ‘is IEnumerable<object>’ doesn’t work even with covariance Thanks @jcotton42 :thumbsupsmiley: ?close Erm