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)