-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. Commented Mar 13, 2020 at 7:46

1 Answer 1

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. Commented Mar 13, 2020 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. Commented Mar 13, 2020 at 12:03
  • 1
    @Duroth making sure your code actually works is what tests are for. Commented Mar 13, 2020 at 13:42

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.