I was just working on some code and caught myself making this error
if (stringName == "firstName" || "lastName")
// Do code
obviously this is wrong and should be
if (stringName == "firstName" || stringName == "lastName")
// Do code
but it just got me thinking in regards to readability would the first be easier? Maybe having some logic that could say unless a new stringName is specified, use the first one?
Really not a question, Im just curious if there is something I dont fully comprehend on the logic behind compiling a statement like this.
I think your proposal would muddy the rules of expression parsing - now, the '==' becomes a quadreny (?) operator, rather than a binary one. I've found myself missing SQL's 'IN' operator, though, and've used something like this:
if (stringName.In("foo", "bar", "baz"))
{
}
// in an extension method class
public static bool In<T>(this T value, params T[] values)
{
return values.Contains(value);
}
The problem is that if works on booleans.
stringName == "firstName"
returns a boolean."lastName"
is a string literal.
||
is a short-circuited boolean or operator that takes booleans on both sides.
In other words, you want to change the definition of ||
which is generally a bad idea.
In theory, you could have the parser infer what you mean... but that becomes ambiguous very quickly.
if (stringName == firstName || lastName)
Looks OK, right? But what exactly is lastName?
What if I did this?
const bool lastName = false;
Also, &&
is the opposite of ||
, but stringName == firstName && lastName
isn't the opposite of the above logic, and in fact wouldn't make sense.
Having the compiler guess at the programmer's intention when the code is clearly wrong in order to fix it is a really, really bad idea.
Even with parentheses, it doesn't make sense. stringName == ("firstName" || "lastName")
looks like you want to test the truth of the two strings, and those strings are always going to be true, and then compare that Boolean result with the string stringName
.
If you add parentheses like this (stringName == "firstName") || "lastName"
, the condition is also always going to be true, since "lastName"
is always true regardless of whether or not stringName
equals "firstName"
.
I like the Ruby way of doing it:
["firstName", "lastName"].include? stringName
You could always use Contains
like others have suggested or write a String extension method to where you could do:
stringName.EqualsOneOf(new[] {"firstName", "lastName"})
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