Search code examples
c#visual-studioextension-methods

C#: Discovering Extension Methods


What tools or techniques do you recommend for discovering C# extension methods in code? They're in the right namespace, but may be in any file in the solution.

Specifically:

  • How can I find all extension methods (and navigate to them) on the current type in the code window?

I do have Resharper (v4), so if that has a mechanism I'm not aware of - please share!


Solution

  • If you have the source then you can search for this Type identifier using regular expressions. Considering the fact that it has to be the first parameter to the function something like this should do the trick:

    \(this:b+:i:b+:i
    

    At least this way you can discover where the extensions methods are defined and add that namespace, then rely on intellisense. Just ran this on a non-trivial project with lots of extensions methods everywhere and it worked a treat. The only false positive was something like this:

    if(this is Blah...
    

    Which we can fix by adding static to our search since the extension methods have to be static:

    static.*\(this:b+:i:b+:i
    

    This won't work for cases like this:

    public
      static ExtensionMethod(
       this int
        iVal) {
    }
    

    But that's kind of the limitation of regular expressions. I am sure certain somebodies can tell you all about the pain of using regular expressions to parse a language.

    Now, what I think is missing from the IDE is the ability to recognise the extension methods that are in a non-imported namespace. Similar to when you know the classname, if you type it up, the IDE will give you a hint to either use it explicitly or import the namespace. After all, that's how I import all my namespaces and frequently find myself trying to do the same to extension methods.