Last active
September 24, 2023 08:17
-
-
Save sandord/400553 to your computer and use it in GitHub Desktop.
Get property name from lambda expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What about a property path (Example: Object.Property.OtherProperty.DesiredProperty)?