Reputation: 365
I know this is a silly mistake, but I can't figure out what's going on. I've created some extension methods and am trying to access them, but the default methods keep getting called:
namespace MyProject
{
public static class Cleanup
{
public static string cleanAbbreviations(this String str) {
if (str.Contains("JR"))
str = str.Replace("JR", "Junior");
return str;
}
public static bool Contains(this String str, string toCheck)
{//Ignore the case of our comparison
return str.IndexOf(toCheck, StringComparison.OrdinalIgnoreCase) >= 0;
}
public static string Replace(this String str, string oldStr, string newStr)
{//Ignore the case of what we are replacing
return Regex.Replace(str, oldStr, newStr, RegexOptions.IgnoreCase);
}
}
}
Upvotes: 2
Views: 509
Reputation: 25221
The compiler will always prefer a type's actual instance methods over matching overloads in extension methods. You'll need to call them without the extension sugar if you want to get around this (or give the extension methods different names):
if(Cleanup.Contains(str, "JR"))
str = Cleanup.Replace(str, "JR", "Junior");
Note that you can omit Cleanup.
from within other methods of Cleanup
- I am including it here for clarity.
Upvotes: 1
Reputation: 125610
Compiler looks for extension methods only when no suitable instance method is found. You can't hide existing instance methods this way.
e.g. There already is Contains
method declared on string
that takes one string
as parameter. That's why your extension method isn't called.
From C# specification:
7.6.5.2 Extension method invocations
The preceding rules mean that instance methods take precedence over extension methods, that extension methods available in inner namespace declarations take precedence over extension methods available in outer namespace declarations, and that extension methods declared directly in a namespace take precedence over extension methods imported into that same namespace with a using namespace directive.
Upvotes: 5