Overload Resolution with Unconstrained Generic Type Testing #6269
-
Consider the following code: using System;
using System.Diagnostics.CodeAnalysis;
public class Test {
public void M<T>(T a, T b) {
var _equal = false;
if(a is IEquatable<T> ae && b is IEquatable<T> be) _equal = ae.Equals(be); // <== Why here object.Equals(object) overload is used instead of IEquatable one despite the cast?
}
}
struct Foo : IEquatable<Foo> {
public int A;
public bool Equals(Foo other) => A == other.A;
} Question: Why in |
Beta Was this translation helpful? Give feedback.
Answered by
PathogenDavid
Jul 12, 2022
Replies: 1 comment 1 reply
-
Because You should just use if(a is IEquatable<T> ae) _equal = ae.Equals(b); And if you expect an oddball scenario where if(a is IEquatable<T> ae) _equal = ae.Equals(b);
else if(b is IEquatable<T> be) _equal = be.Equals(a); |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
fitdev
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Because
IEquatable<T>
provides the methodEquals(T)
, notEquals(IEquatable<T>)
.You should just use
b
directly instead:And if you expect an oddball scenario where
a
andb
have a commonT
but don't both implementIEquatable<T>
you might extend this to: