I was doing a project in groups of 4 people, using C#.NET. While I naturally wrote down something like:
if (var_name == "some_text")
, one of the group members strongly insisted to change that line into if ("some_text" == var_name)
and claim "it's a better programming practice" that she learned from some sensor programmer. No one in our group, not even herself, understood what's the motivation behind this besides it feels more awkward. Is this a better practice or it's just another urban myth?
There's no good reason for this in C#.
In C you can inadvertently forget one of the = signs, and C allows this:
if (x = 5)
Which will compile and always return either true or false (true if the variable was set to any non-zero value, false if it was zero). This was a common source of errors, so writing if (5 == x)
prevents this as the C compiler would complain if you ommitted one of the = signs.
C# however does NOT allow assignment to be treated as a boolean condition, and thus its impossible to make this mistake, so the suggestion is pointless. I'd recommend sticking to the more natural "if x equals 5" style.
Yes, I am not big fan of it.. But there is.. If you mistakenly would use operator assign (=
) instead of compare it will not compile and/or it will immediately crash. At least in "common" programming languages ;-)
This web tells little bit more about it - http://united-coders.com/christian-harms/what-are-yoda-conditions/
I started doing that in college when I took my first C++ class in an effort to not accidentally assign a value I was trying to check against, and it's just always followed me. However, when I use C#, I tend to do:
if (var_name.Equals("some_text"))
Not only does this prevent the accidental assignment, but to me, visually, seeing the Equals() is much more understanding than seeing a ==. Just my two cents.
I was taught to write it backwards when I was taking an intro to programming course in college. We were using C++, and as other answers said, it had a difference in C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With