Skip to content

Instantly share code, notes, and snippets.

@sandord
Last active September 24, 2023 08:17
Show Gist options
  • Save sandord/400553 to your computer and use it in GitHub Desktop.
Save sandord/400553 to your computer and use it in GitHub Desktop.
Get property name from lambda expression
using System.Linq.Expressions;
/// <summary>
/// Returns the name of the specified property of the specified type.
/// </summary>
/// <typeparam name="T">The type the property is a member of.</typeparam>
/// <param name="property">The property expression.</param>
/// <returns>The property name.</returns>
public static string GetPropertyName<T>(Expression<Func<T, object>> property)
{
var lambda = (LambdaExpression)property;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression)
{
UnaryExpression unaryExpression = (UnaryExpression)(lambda.Body);
memberExpression = (MemberExpression)(unaryExpression.Operand);
}
else
{
memberExpression = (MemberExpression)(lambda.Body);
}
var propertyInfo = memberExpression.Member as PropertyInfo;
if (propertyInfo == null)
{
throw new ArgumentException("Does not expess a property.", nameof(property));
}
return propertyInfo.Name;
}
// C# 9 version (works for other member types as well)
public static string GetMemberName<T>(this Expression<T> expression) =>
expression.Body switch
{
MemberExpression m => m.Member.Name,
UnaryExpression { Operand: MemberExpression m } => m.Member.Name,
_ => throw new NotImplementedException(expression.GetType().ToString())
};
@rubemrocha
Copy link

What about a property path (Example: Object.Property.OtherProperty.DesiredProperty)?

@liannoi
Copy link

liannoi commented Feb 15, 2022

@sandord Awesome, thanks!

@ahmedazizaleem
Copy link

Thanks

@01Vladimir10
Copy link

Awesome, thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment