Created
September 9, 2013 20:56
-
-
Save takemyoxygen/6501402 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
public static class ExpressionsEx | |
{ | |
public static string PropertyName<TSource, TResult>(Expression<Func<TSource, TResult>> expression) | |
{ | |
if (expression == null) | |
{ | |
throw new ArgumentNullException("expression"); | |
} | |
if (!(expression.Body is MemberExpression)) | |
{ | |
throw new ArgumentException("Property access exxpressions are supported only"); | |
} | |
var member = ((MemberExpression) expression.Body).Member; | |
if (!(member is PropertyInfo)) | |
{ | |
throw new ArgumentException("Property access exxpressions are supported only"); | |
} | |
return member.Name; | |
} | |
public static string PropertyName2<TSource, TResult>(Expression<Func<TSource, TResult>> expression) | |
{ | |
return expression | |
.EnsureIsNotNull(() => new ArgumentNullException("expression")) | |
.Maybe(e => e.Body as MemberExpression) | |
.Maybe(m => m.Member as PropertyInfo) | |
.EnsureIsNotNull(() => new ArgumentException("Property access exxpressions are supported only")) | |
.Maybe(p => p.Name); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment