CSharp · Console
using System;
using System.Linq.Expressions;
using FluentAssertions;
public static class MyExpressions
{
public static string NameOfProperty<T>(Expression<Func<T>> expression)
{
// Validate argument.
_ = expression ?? throw new ArgumentNullException(nameof(expression));
if (expression.Body.NodeType != ExpressionType.MemberAccess)
{
throw new ArgumentException("The expression must be a member access expression", nameof(expression));
}
// Now that we know we have a member expression in the body
// we can cast it, get a reference to the MemberInfo
// and return the property name.
var memberExpression = (MemberExpression)expression.Body;
return memberExpression.Member.Name;
}
}
public class MyClass
{
public string SomeProperty { get; set; } = "Some Value";
public static void Main()
{
var obj = new MyClass();
var propertyName = MyExpressions.NameOfProperty( () => obj.SomeProperty );
propertyName.Should().Be(nameof(MyClass.SomeProperty));
Console.WriteLine("The name of the property is: {0}", propertyName);
}
}