Last active
September 25, 2015 13:09
-
-
Save Adam--/b2c73dd3d10951e52d42 to your computer and use it in GitHub Desktop.
Extracts a property name string from an 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; | |
using System.Globalization; | |
using System.Linq.Expressions; | |
using System.Reflection; | |
public static class PropertyNameSupport | |
{ | |
private const string ExceptionMessageFormat = "Property expression {0}. Ensure calling with () => Property."; | |
private const string ParameterName = "propertyExpression"; | |
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Changing to base type LambdaExpression causes callers to not be able to use () => Property.")] | |
public static string ExtractPropertyNameFromExpression<T>(Expression<Func<T>> propertyExpression) | |
{ | |
if (propertyExpression == null) | |
{ | |
throw new ArgumentNullException(ParameterName); | |
} | |
var memberExpression = propertyExpression.Body as MemberExpression; | |
if (memberExpression == null) | |
{ | |
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ExceptionMessageFormat, "body is null")); | |
} | |
var property = memberExpression.Member as PropertyInfo; | |
if (property == null) | |
{ | |
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ExceptionMessageFormat, "member is null"), ParameterName); | |
} | |
if (property.GetMethod.IsStatic) | |
{ | |
throw new ArgumentException("member property is static.", ParameterName); | |
} | |
if (property.DeclaringType == null) | |
{ | |
throw new ArgumentException("member property declaring type is null.", ParameterName); | |
} | |
return memberExpression.Member.Name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment