Skip to content

Instantly share code, notes, and snippets.

@hanson-andrew
Created May 3, 2013 16:49
Show Gist options
  • Save hanson-andrew/5511098 to your computer and use it in GitHub Desktop.
Save hanson-andrew/5511098 to your computer and use it in GitHub Desktop.
My implementation of an expression to property name converter. I use it to pull property names in a type-safe way. Usage: public void WhatProperty<T>(Expression<Func<T,object>> expr) { string name = GetPropertyName(expr); }
string GetPropertyName(Expression e)
{
var lambdaExpression = e as LambdaExpression;
if (lambdaExpression != null)
{
return GetPropertyName(lambdaExpression.Body);
}
var unaryExpression = e as UnaryExpression;
if (unaryExpression != null)
{
return GetPropertyName(unaryExpression.Operand);
}
var memberExpression = e as MemberExpression;
if (memberExpression != null)
{
return memberExpression.Member.Name;
}
throw new NotSupportedException(String.Format("Invalid Expression: {0}.", e.ToString()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment