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.
You’re right to think that’s odd and unnecessary, because it is. It’s a completely superfluous
nullor empty check. Frankly, I’d admonish code like that in a code review.is perfectly fine and that’s what I’d use.
No, you’re not missing anything.
Because you’re looking for love in all the wrong places?