Search code examples
c#wsdlsystem.reflection

Code for getting the methods of a class using reflection (excluding system methods such as ToString(),Equals,Hasvalue etc..)


enter image description here

I am working on a wcf proxy generator which generates all the methods dynamically using c#.I am getting the below methods out of which i need only the selected first two.

GetMethods() in reflection returns all the methods(including ToString,Hasvalue,Equals etc) which are not needed for me(i.e Actual types which are defined by me)

Thanks in advance


Solution

  • If I understand correctly, you want methods which:

    • are not getter/setter methods for use be properties
    • are defined on the actual type, not base types
    • do not have a return type of void

      var proxyType = proxyinstance.GetType();
      var methods = proxyType.GetMethods()
          .Where(x => !x.IsSpecialName) // excludes property backing methods
          .Where(x => x.DeclaringType == proxyType) // excludes methods declared on base types
          .Where(x => x.ReturnType != typeof(void)); // excludes methods which return void
      

    All these conditions can also be combined into a single Where call:

    var methods = proxyType.GetMethods().Where(x => 
        !x.IsSpecialName && 
        x.DeclaringType == proxyType && 
        x.ReturnType != typeof(void)
    );