Monday, July 14, 2008

A Modest Proposal

Please, somebody, I'm begging you.

In javascript and C# (and probably C, although I haven't touched it in years) an if statement looks something like this:

if ( i == "one" ) { blah blah blah }

If you need to compare that variable against multiple values, you can do it this way:

if ( i == "one" || i == "two" || i == "three" ) { blah blah blah }

Or you can do it this way:

switch ( i ) case "one": case "two": case "three": { blah blah blah break }

How about doing something like this instead:

if ( i == ( "one" || "two" || "three" ) ) { blah blah blah }

Similarly when assigning a variable using this notation (I forget what the notation is called):

test =
( i == "one" ) ? "number" :
( i == "two" ) ? "number" :
( i == "three" ) ? "number" : "not a number";
// note -- don't know if this works in c# exactly like that, but it
// does in javascript.

How about doing it this way:

test = ( i == ( "one" || "two" || "three" ) ) ? "number" : "not a number";

3 comments:

prash said...

if ( i == ( "one" || "two" || "three" ) ) { blah blah blah }
won't work in C# since it is strongly typed and the order of precedence is for '()' first. So when it evaluates is is looking at "one" as boolean which is not correct.
This works in C since C is loosely typed and anythng >0 is true in C

Michael said...

Then how about something sql-like?

if (i in [ "one", "two", "three"]) { blah blah blah }

prash said...

you can do something similar using LINQ.
create an array of string and use the the .Any feature in it.
for example
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
public static void Anything2()
{
// Create an array of Persons.
List lessthansign Person greaterthansign PersonList = new List lessthansign Person greaterthansign
{ new Person { Name="John", Age=8, Gender="M" },
new Person { Name="Smith", Age=4, Gender="M" },
new Person { Name="Jane", Age=1, Gender="F" }
};


// Determine whether any person over age 1 are also male.
bool male = PersonList.Any(p => p.Age > 1 && p.Gender == "M");

Console.WriteLine(
"There {0} Male persons over age one.",
male ? "are" : "are not any");
}