Another good ques­tion on Stack­Over­flow, and even bet­ter answer from Steven (miles bet­ter than what I man­aged!), the ques­tion was around how to imple­ment an exten­sion method to check whether a cer­tain method has a par­tic­u­lar attribute applied to it, mainly for the pur­pose of unit testing.

In his answer, Steven pro­vided a cou­ple of use­ful exten­sion meth­ods to get the meta­data of a method using lambda expres­sion and then check whether an attribute with the spec­i­fied type has been applied to it:

public static MethodInfo GetMethod<T>(this T instance, Expression<Func<T, object>> methodSelector)
{
    // Note: this is a bit simplistic implementation. It will
    // not work for all expressions.
    return ((MethodCallExpression)methodSelector.Body).Method;
}

public static MethodInfo GetMethod<T>(this T instance, Expression<Action<T>> methodSelector)
{
    return ((MethodCallExpression)methodSelector.Body).Method;
}

public static bool HasAttribute<TAttribute>(this MemberInfo member) where TAttribute : Attribute
{
    var attributes = member.GetCustomAttributes(typeof(TAttribute), true);
    return attributes.Length > 0;
}

Nice, eh? I thought so too! Don’t for­get to give him some much deserved up vote!

Share

Leave a Reply