1

I have an extension method on string class

public static bool Contains(this string original, string value, StringComparison comparisionType)
{
   return original.IndexOf(value, comparisionType) >= 0;
}

But impossible to get the method by reflection

IEnumerable<MethodInfo> foundMethods = from q in typeof(string).GetMethods()
                                       where q.Name == "Contains"
                                       select q;

foundMethods only obtain the Contains(string) method why? Where are the other Contains methods?

Francis
  • 486
  • 3
  • 21
  • 2
    possible duplicate of [C# Reflection to Identify Extension Methods](http://stackoverflow.com/questions/299515/c-sharp-reflection-to-identify-extension-methods) – Grant Thomas Dec 19 '11 at 14:09
  • Possible duplicate of [Reflection to Identify Extension Methods](http://stackoverflow.com/questions/299515/reflection-to-identify-extension-methods) – Massimiliano Kraus Apr 13 '17 at 14:35

3 Answers3

3

It's not a method declared in the String class, so GetMethods can't see it. The fact that an extension method is in scope depends on whether the namespace that declares it is imported, and reflection doesn't know anything about that. Keep in mind that extension are just static methods, with syntactic sugar that makes it look like they are instance methods.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
1

You cannot use the simple reflection method you have listed in the question to find extension methods.

You will have to look at ExtensionAttribute on classes and methods and verify that the first parameter type is string. As as extension method can be defined in any assembly you will have to do this for assemblies of interest

parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
0

Your Contains Method is not in String class, therefore , you cannot obtain Contains method with typeof(string).GetMethods().

To obtain what you need you can use code

public partial String
{
   public static bool Contains(this string original, string value, StringComparison comparisionType)
   {
       return original.IndexOf(value, comparisionType) >= 0;
   } 
}

But code has a problem that String class cannot be static so you cannot use this parameter.

So your should define this Contains method in any static Class.

you can obtain with using code:

    public static StringDemo
    {
       public static bool Contains(this string original, string value, StringComparison comparisionType)
       {
           return original.IndexOf(value, comparisionType) >= 0;
       } 
    }

IEnumerable<MethodInfo> foundMethods = from q in typeof(StringDemo).GetMethods()
                                       where q.Name == "Contains"
                                   select q;
Sinan AKYAZICI
  • 3,942
  • 5
  • 35
  • 60