Sometimes, a value must be checked for equality with a constant. In such cases, I've always seen the code like this:
if (!string.IsNullOrEmpty(text))
{
if (text == "Some text here")¹
{
// Do something here.
}
}
In my case, I would rather write:
if ("Some text here".Equals(text))
{
// Do something here.
}
After all, if text
is null
, Equals
will return false
, which is expected. The inversion of a constant and a variable feels strange, but is still understandable for a beginner, and avoids the NullReferenceException
which would be thrown with text.Equals("Some text here")
.
Am I missing something?
Why all source code I've seen use the syntax from the first example, and never from the second one?
¹ In real code, it would rather be a constant or a readonly field. To shorten the examples, I put the strings inline.