views:

69

answers:

2

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));
}
+10  A: 

You can't override the function, but you can make an extension method for this:

public static class StringExtensions {
     public static bool ContainsAny(this string theString, IEnumerable<string> items)
     {
         // Add your logic
     }
}

You'd then call this just like a normal method on a string, provided you reference the assembly and include the namespace:

String helloworld = "Hello World";
String[] items = new string[] { "He", "el", "lo" };

if (helloworld.ContainsAny(items)) { 
   // Do something
}

(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...)

Reed Copsey
Thanks a lot. This is what I just needed.
Jronny
BTW, the functions need to be static too right?
Jronny
@Jronny: Yes - It was a typo in my post. Thanks for pointing it out (I've corrected it now).
Reed Copsey
Thanks a lot...
Jronny
+3  A: 

Why not keep things simple and use the Any extension method?

string helloworld = "Hello World";
string[] items = { "He", "el", "lo" };
if (items.Any(item => helloworld.Contains(item)))
{
    // do something
}
Ahmad Mageed
it's more simple if we just do if(string.Contains(items))... But I might use your code inside the function. Thanks.
Jronny