zaterdag 24 mei 2008

Making shortcuts for case-insensitive String.IndexOf

Extension methods in C# allow programmers to correct situations where .NET does not provide the easiest way to do things. Most of the times when I want to do a String.IndexOf, it is the case insensitive version I need. .NET defaults to the most sensitive version. In c# the following code is needed to perform such a call:


if (str.IndexOf("test", StringComparison.OrdinalIgnoreCase) >= 0) {
...
}
The extension methods for the IndexOf are called IndexOf_CI. They cannot be called IndexOf since the parameter signature is the same. Where CI stands for Case-Insensitive. Below I created the overloads for IndexOf the framework offers.


public static int IndexOf_CI(this String str, string value)
{
return str.IndexOf(value, StringComparison.OrdinalIgnoreCase);
}

public static int IndexOf_CI(this String str, char value)
{
return str.IndexOf(value.ToString(), StringComparison.OrdinalIgnoreCase);
}

public static int IndexOf_CI(this String str, string value, int startIndex)
{
return str.IndexOf(value, startIndex, StringComparison.OrdinalIgnoreCase);
}

public static int IndexOf_CI(this String str, char value, int startIndex)
{
return str.IndexOf(value.ToString(), startIndex, StringComparison.OrdinalIgnoreCase);
}

public static int IndexOf_CI(this String str, string value, int startIndex, int count)
{
return str.IndexOf(value, startIndex, count, StringComparison.OrdinalIgnoreCase);
}

public static int IndexOf_CI(this String str, char value, int startIndex, int count)
{
return str.IndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
The code becomes a lot shorter en more friendly to the eye:


if (str.IndexOf_CI("test") >= 0) {
...
}
To complete this library also the IndexOfAny and LastIndexOf need to be supplied with case-insensitive versions.

Geen opmerkingen: