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
/// <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.
/// </param>
/// <returns>
/// The property name.
/// </returns>
public static string GetPropertyName<T>(System.Linq.Expressions.Expression<Func<T, object>> property)
{
System.Linq.Expressions.LambdaExpression lambda = (System.Linq.Expressions.LambdaExpression)property;
System.Linq.Expressions.MemberExpression memberExpression;
if (lambda.Body is System.Linq.Expressions.UnaryExpression)
{
System.Linq.Expressions.UnaryExpression unaryExpression = (System.Linq.Expressions.UnaryExpression)(lambda.Body);
memberExpression = (System.Linq.Expressions.MemberExpression)(unaryExpression.Operand);
}
else
{
memberExpression = (System.Linq.Expressions.MemberExpression)(lambda.Body);
}
return ((PropertyInfo)memberExpression.Member).Name;
}
@Chris-ZA
Copy link

Awesome! Thank you!

@VGBenjamin
Copy link

Exactly what I was searching for!
Thanks

@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