0

Once I found a realy great method on a project I was working on, and I can use it to get the name of a property of a class, strong typed, which realy comes in handy when refactoring or finding references. The downside of the code is I realy don't understand how it works, and normally I resent that, but in this case I'll accept it.

The code is this:

public static class ObjectHelper<T>
{
    public static string GetPropertyName<TProp>(Expression<Func<T, TProp>> expr)
    {
        var node = expr.Body as MemberExpression;

        if (ReferenceEquals(null, node))
        {
            throw new InvalidOperationException("Expression must be of member access");
        }

        return node.Member.Name;
    }
}

And I can use it on a class CompanyPersonProfileViewModel with a property CountryId like this:

string s = ObjectHelper<CompanyPersonProfileViewModel>.GetPropertyName(z => z.CountryId);

Anyway, since I don't know how it works (if YOU do, I'll like the explanation too), I don't know how to adjust the code for my other wish: get the name of a method strong typed.

So when I have the same class and a method named GetAllCountries(), that I can type this:

string s = ObjectHelper<CompanyPersonProfileViewModel>.GetMethodName(z => z.GetAllCountries);

(or something similar)

Christos
  • 53,228
  • 8
  • 76
  • 108
Michel
  • 23,085
  • 46
  • 152
  • 242
  • @Rawling : I don't see the answer in that question. As I stated I don't understand the code I posted, so a link to an answer with 'sort of' an answer is not a duplicate in my opionion – Michel Jun 24 '14 at 08:26
  • Does the line `MethodCallExpression callExpression = expression.Body as MethodCallExpression` in the answer there not give you a way to change your line `var node = expr.Body as MemberExpression` to do what you want? – Rawling Jun 24 '14 at 08:29
  • (And the `callExpression.Method.Name` line further down.) – Rawling Jun 24 '14 at 08:31
  • I've got it figured out, thanks. – Michel Jun 25 '14 at 07:49
  • Check my answer at: http://stackoverflow.com/questions/9412182/get-the-names-of-interface-methods-strong-typed/32245698#32245698 – ShloEmi Aug 27 '15 at 13:32

0 Answers0