Oct 12 2009

Params & Extension Methods

Category: C#,Extension MethodsWil @ 10:25 am

This morning I was working on some legacy code (code I find that has no corresponding unit tests assigned to it) and found myself wanting the C# equivalent of the SQL “NOT IN” and “IN” statements. For example,

SELECT COUNT(*) FROM
WHERE NOT IN { }

So, I wrote a simple little extension method class to do just that:

static public class Extensions
{
	static public bool IsIn(this Int32 value_, params Int32[] list_)
	{
		// LINQ is less efficient...
		// return list_.Where(v => { return v == value_;}).Count() > 0;
		// ...than this:
		foreach (var value in list_)
			if (value == value_)
				return true;

		return false;
	}
	static public bool NotIn(this Int32 value_, params Int32[] list_)
	{
		return !IsIn(value_, list_);
	}
}

Now you can write code like this:

public void Example1 (Int32 [] someList_)
{
   if (5.IsIn(someList_)
      DoSomethingSexy();
}

… or like this:

public void Example2 (Int32 value_)
{
   if (value_.NotIn(_myList))
      DoSomethingElseSexy();
}

Enjoy!

One Response to “Params & Extension Methods”

  1. Casey says:

    Nice. You have to love extension methods. Depending on how you’re using this method, you might want to consider making it generic. Then you’re not limiting yourself to Int32. Food for thought. Great post!

Leave a Reply

Spam Protection by WP-SpamFree Plugin

Get Adobe Flash playerPlugin by wpburn.com wordpress themes