Thursday, February 28, 2008

.NET Extensions Anyone?

If you haven't seen .NET extension methods in action, they're pretty interesting. What are they, you ask? Let's say you have an existing .NET class provided by an external vendor. Let's say that vendor is Microsoft. You want to add a new function to, I don't know, lets say the string class. There's not a hope in hell that you'll get Microsoft to add it for you.

Of course, you could build your own string class, override one of the existing functions, or add a new one, but that seems like a lot of work. Here's an easy way to add a new function to the class, without having to use inheritance at all. And the best part is that within seconds, this class will show up in your Intellisense.

This function must be in a static class, and part of your own project / namespace or compiled into a DLL while you include in your project.

I wrote this function as I have been trying to find an efficient way to build dynamic Lambda queries for LINQTOSQL, but unfortunately, this won't work as 'FindWickedString' is not a function which can be interpreted by SQL Server, and the lambda function I am building executes on SQL Server. So I'll keep digging on the dynamic lambdas, but this is fun as an exercise. Wait. Did I say coding was fun. Egads. I meant work.




public enum WildcardMethod { Contains, StartsWith, EndsWith, Exact }

static class Extensions
{
public static bool FindWickedString(this string value, string checkValue, WildcardMethod method)
{
switch (method)
{
case WildcardMethod.Contains:
{
if (value.Contains(checkValue))
return true;
break;
}
case WildcardMethod.StartsWith:
{
if (value.StartsWith(checkValue))
return true;
break;
}
case WildcardMethod.EndsWith:
{
if (value.EndsWith(checkValue))
return true;
break;
}
case WildcardMethod.Exact:
{
if (value == checkValue)
return true;
break;
}

default:
break;
}

return false;
}

No comments: