I am writing an extension method where I happen to need the field name that the extension method is needed within the extension method. I can not figure out how to do this.
My code:
Extension method:
public static Validate Demand<T>(this T parameter) { string name = ... var field = GetField(parameter); return Validation.CreateValidation(parameter, field, name); }
Use case:
void SomeMethod(T someParameter) { someParameter.Demand(); }
I want name to hold someParameter.
You can’t. It would be nice in a few cases, particularly for argument checking, but it’s just not possible. As an example of where it would be handy, I have this method:
which I have to call with:
It’s better than nothing, but it would be nice not to have to supply the ‘foo’ bit. Unfortunately, there’s just no way of doing it. You could probably write a post-build IL rewriter which determined how the method was called and rebuilt it from that, but that’s rather more work than the benefit, I suspect 🙂