I remember long ago reading somewhere that to check a String object against a literal (or a constant, etc.) string, a way to skip null check is:
string a;
// do something
if("some literal string".Equals(a))
Console.WriteLine("equal");
is preferred rather than
string a;
// do something
if(a!=null && a.Equals("some literal string"))
Console.WriteLine("equal");
to skip checking against null. However cannot find information about it right now; do you have any objections or concerns about the former one?
You’re probably thinking about Java, where you need to use
equalsin order to perform a true value equality check for strings;==would just compare references for identity.C#, however, has operator overloading – and
stringoverloads==for equality. So it’s fine to write:The
==operator handlesnullon either (or both) sides of the comparison:Note, however, that the overload will only be used if the compile-time type of both expressions is
string. For example, if you had:… then that will compare references instead of using the overloaded operator.