For example, I need to see if a string contains a substring, so I just do:
String helloworld = "Hello World";
if(helloworld.Contains("ello"){
//do something
}
but if I have an array of items
String helloworld = "Hello World";
String items = { "He", "el", "lo" };
I needed to create a function inside the String class that would return true if either of the items inside the array is contained in the string, for example.
I would like to override the function Contains(string) with Contains(IEnumerable) for this scenario, instead of creating a function in another class. Is it possible to do this, and if so, how can we override the function? Thank you very much.
So here goes the complete solution (thanks guys):
public static bool ContainsAny(this string thisString, params string[] str) {
return str.Any(a => thisString.Contains(a));
}
Why not keep things simple and use the
Any
extension method?You can't override the function, but you can make an extension method for this:
You'd then call this just like a normal method on a string, provided you reference the assembly and include the namespace:
(Granted, you could call this "Contains", like the standard string method, but I would prefer to give it a more explicit name so it's obvious what you're checking...)