posted 6/18/2011 by Raghav Khunger
I was working with string.Compare method today where I had a requirement in which I needed to compare a string by ignoring the case but I found that the string.Compare method only accepts one arguement which is the string to be checked only. So I decided to make my own Compare extension method for string class. I am writing this blog to explain the same what I did in my case to compare the strings igonring case. Extension class
using System; namespace MyConsole { public static class MyExtensions { public static bool Contains(this string sourceString, string stringToCheck, StringComparison comparison) { return sourceString.IndexOf(stringToCheck, comparison) >= 0; } } }
Below is the screen which shows the magic of extension method. Because of it the second argument is availaible to string.Compare method from where user can enter different kind of options provided by StringComparison enum.Let's test the above extension method with a practical example. Let's say we have a source string "This IS a GamE" and we want to check whether "game" string exists in it or not. Now in order to test it we have to ignore the case comparison. Now here comes the role of our extension method. We can provide now a second argument of type StringComparison and in this case we are going to provide "OrdinalIgnoreCase" option which compare strings using ordinal sort rules and ignoring the case of the strings being compared. Below is the sample code:
using System; using MyConsoleExtensions; namespace MyConsole { class Program { static void Main(string[] args) { string sourceString = "This IS a GamE"; string stringToCheck = "game"; bool isPresent = sourceString.Contains(stringToCheck, StringComparison.OrdinalIgnoreCase); Console.WriteLine(isPresent.ToString()); Console.ReadLine(); } } }
Below is the output of above test:
Do let me know your feedback, comments.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18