views:

54

answers:

3

Is this code wrong? It's just not returning anything:

public IEnumerable<string> GetMethodsOfReturnType(Type cls, Type ret)
{
   var methods = cls.GetMethods(BindingFlags.NonPublic);
   var retMethods = methods.Where(m => m.ReturnType.IsSubclassOf(ret))
                           .Select(m => m.Name);
   return retMethods;
}

It's returning an empty enumerator.

Note: I'm calling it on a ASP.NET MVC Controller looking for ActionResults

GetMethodsOfReturnType(typeof(ProductsController), typeof(ActionResult));
+1  A: 
BindingFlags.NonPublic | BindingFlags.Instance

Where(m => ret == m.ReturnType || m.ReturnType.IsSubclassOf(ret))
Andrey
+1  A: 

Two changes that could possibly make this work:

public IEnumerable<string> GetMethodsOfReturnType(Type cls, Type ret)
{
   var methods = cls.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
   var retMethods = methods.Where(m => m.ReturnType.IsSubclassOf(ret) || m.ReturnType == ret)
                           .Select(m => m.Name);
   return retMethods;
}
BFree
+3  A: 

Others have pointed out fixes, but I'd like to suggest an alternative to IsSubclassOf as well as including public methods:

public IEnumerable<string> GetMethodsOfReturnType(Type cls, Type ret)
{
   // Did you really mean to prohibit public methods? I assume not
   var methods = cls.GetMethods(BindingFlags.NonPublic | 
                                BindingFlags.Public |
                                BindingFlags.Instance);
   var retMethods = methods.Where(m => m.ReturnType.IsAssignableFrom(ret))
                           .Select(m => m.Name);
   return retMethods;
}

With IsAssignableFrom, you don't need to have the extra "is the return type exactly the same as the desired type" test, and also it will work with interfaces.

Jon Skeet
Hard to know, but I would assume in production code the controller actions of interest would be only those that are public, perhaps filtered by only those not having the NonActionAttribute.
tvanfosson
You're right tvanfsoon. +1 for your insight!
Aren