http://blogs.clariusconsulting.net/kzu

Daniel Cazzulino's Blog

Go Back to
kzu′s Latest post

Tip: how to tell a regular method apart from property getter/setters and event add/remove

Rather than typical code like:

private static MethodInfo GetFirstMethodWithReturnType(Type type)
{
    return
        type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
            .Where(method => !method.Name.StartsWith("get_") &&
                                !method.Name.StartsWith("set_") &&
                                !method.Name.StartsWith("add_") &&
                                !method.Name.StartsWith("remove_"))
            .FirstOrDefault(method => (method.ReturnType != typeof(void)));
}

You can simply do:

private static MethodInfo GetFirstMethodWithReturnType(Type type)
{
    return
        type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
            .Where(method => !method.IsSpecialName)
            .FirstOrDefault(method => (method.ReturnType != typeof(void)));
}

IsSpecialName returns true for property getters/setters and event add/remove :)

Comments