C # Operators and readability

I just worked on some code and caught myself making this mistake

if (stringName == "firstName" || "lastName")
   // Do code 

obviously this is wrong and should be

if (stringName == "firstName" || stringName == "lastName")
   // Do code 

but I just thought it would be easier to read in the first place? Maybe with some logic that could tell if a new stringName is not specified, use the first?

Actually not a question, I'm just wondering if there is something that I do not fully understand from the compilation logic of such a statement.

+5
source share
10 answers

The problem is that if it works with boolean values.

stringName == "firstName"returns a boolean value.
"lastName"- string literal.

|| , .

, ||, .

, ... .

if (stringName == firstName || lastName)

, ? lastName?

, ?

const bool lastName = false;

, && ||, stringName == firstName && lastName .

+10

, - '==' quadreny (?), . , , SQL 'IN', - :

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);
}
+11

, , , .

+6

. stringName == ("firstName" || "lastName") , , , stringName.

, (stringName == "firstName") || "lastName", , "lastName" , stringName "firstName".

Ruby :

["firstName", "lastName"].include? stringName

Contains, String , :

stringName.EqualsOneOf(new[] {"firstName", "lastName"})
+2

, , , , - . , , stringName "firstName" "lastName". .

.

+1

, operator||(string,string) .. , Equals, , . , .

, - :

if(new string[]{"firstName","lastName"}.Contains(stringName))
    // code
+1

, Contains() , ..

string[] ValidNames = new string[] { "firstName", "lastName"};

if(ValidNames.Contains(stringName))
{
    //Do Code
}
+1

SQL:

if(stringName in ("firsName", "lastName"))
{
}
+1

, , :

if ((stringName == "firstName") || (stringName == "lastName"))
   // Do code

.

0

FCL , , , #, , . .

Here is an example (just one of many) that you can find one or more lines at a time in an array of strings or apply any other criteria that, in your opinion, match this set of strings. Indentation, spacing, and code comments play a large role in understanding this code example, as with any code.

        bool found = Array.Exists(
            // array of strings to search
            new[] { "c#", ".net", "programming", "design patterns", "work", "play", "bits", "bytes", "break" },
            // criteria - can even satisfy multiple conditions simultaneously if desired
            str => (str == ".NET" || str == "work") //look for ".NET" or "work"
            );
0
source

All Articles