Question

as the title says: I need a NDepend rule (CQLinq) for C#/.net code, that fires whenever instances of a given type are compared using == (reference comparison). In other words, I want to force the programmer to use .Equals.

Note that the type in question has no overloaded equality operator.

Is this possible? If so, how? :)

Thanks, cheers, Tim

Était-ce utile?

La solution

With the following code with see that for value type, == translate to the IL instruction: ceq. This kind of usage cannot be detected with NDepend.

     int i = 2;
     int j = 3;
     Debug.Assert(i == j);
     var s1 = "2";
     var s2 = "3";
     Debug.Assert(s1 == s2);

However for reference types we can see that a operator method named op_Equality is called.

 L_001d: call bool [mscorlib]System.String::op_Equality(string, string)

Hence we just need a CQLinq query that first match all method named op_Equality, and then list all callers of these methods. This can look like:

let equalityOps = Methods.WithSimpleName("op_Equality")
from m in Application.Methods.UsingAny(equalityOps)
select new { m, 
             typesWhereEqualityOpCalled = m.MethodsCalled.Intersect(equalityOps).Select(m1 => m1.ParentType) }

This seems to work pretty well :)

enter image description here

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top