Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Operators and readability

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.

like image 447
Leroy Jenkins Avatar asked Oct 23 '09 20:10

Leroy Jenkins


4 Answers

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);
}
like image 154
Michael Petrotta Avatar answered Oct 04 '22 11:10

Michael Petrotta


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.

like image 24
Powerlord Avatar answered Oct 04 '22 12:10

Powerlord


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.

like image 34
tvanfosson Avatar answered Oct 04 '22 12:10

tvanfosson


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"})
like image 21
Sarah Vessels Avatar answered Oct 04 '22 10:10

Sarah Vessels