Using == or Equals for string comparison

我的未来我决定 提交于 2019-11-27 14:02:59

问题


In some languages (e.g. C++) you can't use operators like == for string comparisons as that would compare the address of the string object, and not the string itself. However, in C# you can use == to compare strings, and it will actually compare the content of the strings. But there are also string functions to handle such comparisons, so my question is; should you?

Given two strings:

string aa = "aa"; 
string bb = "bb";

Should you compare them like this:

bool areEqual = (aa == bb); 

Or should you use the Equal function, like this:

bool areEqual = aa.Equals(bb); 

Is there any technical difference anyway? Or reasonable arguments for best practice?


回答1:


I wouldn't use:

aa.Equals(bb)

unless I knew aa couldn't possibly be null. I might use:

string.Equals(aa,bb)

But I'd mainly use that it I wanted to use one of the specific StringComparison modes (invariant, ordinal, case-insensitive, etc). Although I might also use the StringComparer implementations, since they are a bit easier to abstract (for example, to pass into a Dictionary<string, Foo> for a case-insensitive ordinal dictionary). For general purpose usage,

a == b

is fine.




回答2:


This is the implementation of the operator:

    public static bool operator == (String a, String b) {
       return String.Equals(a, b);
    }

Don't lose any sleep over this.




回答3:


There is no technical difference (unless aa is null). Use whatever looks better to you. In my opinion, using operator overloads makes the code clearer.

Use functions when you need (or might need in future) their additional arguments (as in CompareTo())




回答4:


Best-practise-wise, I would tend to always use an Equals() function for string comparison. This makes it clear when someone else reads your code that you specifically want the strings compared.




回答5:


generally speaking, == does pointer equality, while .equals checks whether the attributes are equal. So if you did something like

a = 'a';
b = 'a';
bool c = (a == b);
bool d = (a.Equals(b))

then c should return false and d should be true.



来源:https://stackoverflow.com/questions/1968787/using-or-equals-for-string-comparison

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