makcis
makcis

Reputation: 125

How to find function which return any type

I have class with methods. For example

public class Foo
{
    public int Method1()
    {
        return 1;
    }

    public int Method2()
    {
        return 2;
    }

    public int Method3(int i)
    {
        return i;
    }

}

Now I would have function which will find all methods from above class such that are returning int and don't have any parameters.

I think, I can use reflection:

    Type type = o.GetType();
    MethodInfo[] m = type.GetMethods();

But it give me all methods. So how can I get methods with criteria?

Upvotes: 0

Views: 69

Answers (1)

Lee
Lee

Reputation: 144176

var matches =  m.Where(mi => mi.ReturnType == typeof(int) && mi.GetParameters().Length == 0);

Note this return all matching methods in all subtypes. If you want only the methods declared in your type you can use the overload of GetMethods:

var matches = o.GetType()
    .GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
    .Where(mi => mi.ReturnType == typeof(int) && mi.GetParameters().Length == 0);

Upvotes: 5

Related Questions