-4

It's mind bending experiencing reading code like :

"Aggregation".Equals(evt.Id))

I was unsuccessful in trying to talk the person out of this style, maybe I'm wrong? Or maybe I wasn't articulate enough, hence the post here.

1
  • 1
    Could evt.Id be null? Perhaps. You do not want to call methods on null. "Aggregation" is not null, for sure. Although, why not ==? Yeah, use == instead. If you had a reason not to, you probably should be using an equality comparer. – Theraot Mar 13 '20 at 7:46
5

No, it's not justified.

It makes some sense to do this for string comparisons in Java where calling .equals on a string variable can result in a NullPointerException, so:

myString.equals("foo")

Can be made safer by doing:

"foo".equals(myString)

This is not really relevant in C# which uses the == operator for string comparisons. This is safe to use with null references. The same is true of String.Equals.

3
  • In languages that use == for comparisons, Yoda conditions are often used to prevent accidental assignments in conditions (if (myValue = "foo") then ...). Some languages disallow assignments in condition blocks for this reason. I believe C# is among those? Which would indeed mean it's a lot harder to justify. – Duroth Mar 13 '20 at 10:12
  • 2
    @Duroth In C# a statement like if (myValue = "foo") { ... } yields a compilation error saying that 'string' cannot be implicitly converted to 'bool'. Even when using if (myBoolValue = true) { ... }, the compiler issues a warning saying that the expression is constant and thr author probably meant to use == instead of =. So yeah, in C# there is usually no need for yoda conditions. – helb Mar 13 '20 at 12:03
  • @Duroth making sure your code actually works is what tests are for. – Ant P Mar 13 '20 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.