I am new to C# and found two ways to compare strings. Whats the difference between these approaches?
var a = "hello";
var b = "hello";
a.Equals(b);
string.Equals(a, b);
CodePudding user response:
The difference is that a.Equals(b)
throws an exception if a is null:
string a = null;
string b = "hello";
a.Equals(b); // throws a NullReferenceException
string.Equals(a, b); // returns false
Especially when you know that the strings could be null (for example user inputs) it's safer to use string.Equals(a, b)
.