0

Possible Duplicate:
get methodinfo from a method reference C#

This is most likely something simple but so far I have not come up with anything on how to do this.

I want to be able to get the name of a method in two different ways. Please note I want a method name, not a property name.

1) Inside of a class like ClassA<T>, looking like:

var name = GetMethodName(x => x.MethodA);

2) Outside of a class, looking like:

var name = GetMethodName<ClassA<object>>(x => x.MethodA);
var name = GetMethodName<ClassB>(x => x.MethodB);

How might I do this exactly?

Thanks!

Community
  • 1
  • 1
Landin Martens
  • 3,283
  • 12
  • 43
  • 61

1 Answers1

1

You don't need lambdas (x => x.MethodA, etc). That's just confusing the issue (and hiding the method of interest: the MethodA bit would be hidden from your GetMethodName method).

Instead, you can use reflection to get a MethodInfo object, which then has a Name property.

For example:

MethodInfo sm = typeof(SomeClass).GetMethod("SomeMethod");
string methodName = sm.Name;

Here methodName will be the string "SomeMethod". (Of course, in this simple case we've used the class name to get the MethodInfo object, so it's somewhat circular and we might as well have just used the hard-coded "SomeMethod" string instead!)

Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93
  • This will not work for me, that is why I said I need it using a lambda expression. Reflection using strings does not work once obfuscated as the method names change from "MethodA" to "ASNDKAMSDKMASD" for example. If I use it like my example, then when the method name is renamed the reflection does not break. That is why I must be able to do it using the way I asked for. – Landin Martens Oct 14 '12 at 20:25
  • Okay, I didn't realise it was possible to retrieve the target method from a lambda expression but it appears it is. See the possible duplicate question I've linked to in my comment above. – Matthew Strawbridge Oct 14 '12 at 20:53
  • Thanks, I think that will solve my issue! – Landin Martens Oct 15 '12 at 20:34