I want to write an extension method that tests if an attribute is applied on a method call, and I'd like to specify the method as a lambda expression. Currently, I have the following (working) approach, but I really don't like the way this code looks:
// Signature of my extension method:
public static bool HasAttribute<TAttribute, TDelegate>(this Expression<TDelegate> method)
// Usage (current code)
Expression<Func<AccountController, LogInModel, string, ActionResult>> mut = (c, m, s) => c.LogIn(m, s);
mut.HasAttribute<ExportModelStateAttribute, Func<AccountController, LogInModel, string, ActionResult>>().ShouldBeTrue();
As you can see, I have to specify the delegate type twice, and neither time does it look pretty... I'd like to have something more like
// Usage (if I had my way...)
var mut = (c, m, s) => c.LogIn(m, s);
mut.HasAttribute<ExportModelStateAttribute>().ShouldBeTrue();
but I realize that might be asking a tad bit too much.
Is there any way I could refactor away the type arguments from my current code?
The reason I have the TDelegate
type argument there in the first place, is that I want to use this regardless of method signature and return type, and depending on the number of input arguments and whether the method in question is a void
or a function, TDelegate
needs to vary. I don't want to have one different implementation for each number of input arguments to the method I test...
Update:
As Jay points out in a comment, I apparently don't need to specify the TDelegate
type argument in the call to HasAttribute<>
. The code now looks like this:
Expression<Func<AccountController, LogInModel, string, ActionResult>> mut = (c, m, s) => c.LogIn(m, s);
mut.HasAttribute<ExportModelStateAttribute>().ShouldBeTrue();
It's much better, but I still think the first line is pretty messy. Could it be even better?