Daniel Cazzulino's Blog : Tip: how to tell a regular method apart from property getter/setters and event add/remove

Subscriptions

News

Source code published in this blog is public domain unless otherwise specified.

 

kzu in LinkedIn

  Microsoft MVP Profile

 Contact

Post Categories

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 :)

posted on Friday, February 06, 2009 7:02 PM by kzu

# Tip: how to tell a regular method apart from property getter/setters and event add/remove @ Friday, February 06, 2009 7:09 PM

Rather than typical code like: private static MethodInfo GetFirstMethodWithReturnType(Type type) { return

Anonymous