Warning on == used on references (Visual Studio or ReSharper)

心不动则不痛 提交于 2020-01-06 04:54:06

问题


According to the documentation of the == operator in MSDN,

For reference types other than string, == returns true if its two operands refer to the same object.

But, to be honest, I never check if two references are the same with ==.
I prefer using ReferenceEquals(obj1, obj2) and so do the default override of the Equals function.

Therefore, in my projects, when the == operator is used on other types than string, equals to a bug.

Is there a way to trigger a warning/error through Visual Studio or ReSharper when == is used on references (apart from string)?


回答1:


It is not a global solution, but if we want to consider only some classes, the CannotApplyEqualityOperatorAttribute in JetBrains.Annotations does the trick.

[CannotApplyEqualityOperator]
public sealed class NonEquatable { }

public sealed class OtherClass
{
    public bool DoForbiddenStuff()
    {
        var obj1 = new NonEquatable();
        var obj2 = new NonEquatable();

        // ERROR! 'Cannot apply equality operator to type marked by CannotApplyEqualityOperatorAttribute'
        return obj1 == obj2; 
    }
}

Still waiting to see if there is a more generalized alternative.




回答2:


As suggested, I created an extension to do that.

If you're interested, here is the link to the extension in the marketplace.
And here is the link to the source code.

At the moment it does not check if the object has an override for the operators "==" and "!=". Whoever wants to contribute is more than welcome to do so.



来源:https://stackoverflow.com/questions/59460431/warning-on-used-on-references-visual-studio-or-resharper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!