Archive

Archive for the ‘C#’ Category

A more concise way to match values in C#

January 28th, 2009

From time to time, a developer will need to match a value in a series of values to accomplish conditional logic of some sort. Recently, while working with a project which had a status value, I needed a concise way match the value and do something useful.

Normally, I would write C# code that looks like this:

// Hard-coded for example
string status = "ww";

if (status == "ww" || status == "r" || status == "bw" ||
    status == "nb" || status == "qb" || status == "nt")
{
	// do something interesting
}
else if...
else if...
else...

However, after my hands tired out from typing (even with intellisense), I came up with the following:

// Hard-coded for example
string status = "ww";

if (new[] { "ww", "r", "bw", "nb", "qb", "nt" }.Contains(status))
{
    // do something interesting
}
else if...
else if...
else...

If the array of values contains an equal value to the status, then success. As you can see, the code is much easier to read and requires less typing. Enjoy!

[Update: Changed to use implicitly typed array (requires C# 3.0) instead of List<string>. Thanks manitra!]

rgillette C#, Code , ,