In Extension Method for C#

January 18, 2012

By

Sometimes, you end up with code that looks like this:

if (!c.Equals('.') && !c.Equals('_') && !c.Equals(' ') && !c.Equals('-'))
{ /* whatever */ }

Obviously, this works, but it’s not very obvious, and it can get pretty unwieldy (imagine if those characters were all enums…).  Wouldn’t it be nice to have a straightforward way to say “if the value is in this set of values…”, like you do with the SQL keyword IN?

Well, now you have one.

public static bool In<T>(this T itemToLookFor, params T[] itemsToLookIn)
{
return itemsToLookIn.Contains(itemToLookFor);
}

Stick this handy extension method in a static class in your project, and then you’ll be able to rewrite the first code as:

if (!c.In('.', '_', ' ', '-')) { /* whatever */ }

“But wait!” you cry. “Couldn’t you just write this:”

if (!new[] { '.', '_', ' ', '-' }.Contains(c)) { /* whatever */ }

Yes, and that would function just as well. But, consider how the code reads. Using In(), the code reads like you would say it: “If not ‘c’ in ‘.’, ‘_’…”. In the second example, the order of the variables is reversed, and the variable we’re looking at gets lost in the Contains call. So, I find it much cleaner to use In() when possible.

Software Engineer
Geoffrey Lehr

In addition to programming, this multitalented (and handsomely modest!) developer enjoys playing & composing music, reading SF and playing video games.

Leave a Comment