I found a post with a great answer for a problem I have, but I can\'t seem to find a small detail I\'m looking for.
public class myModel
{
[JsonProperty(P
Here's a way of doing it while keeping things strongly typed:
public static string GetPropertyAttribute<TType>(Expression<Func<TType, object>> property)
{
var memberExpression = property.Body as MemberExpression;
if(memberExpression == null)
throw new ArgumentException("Expression must be a property");
return memberExpression.Member
.GetCustomAttribute<JsonPropertyAttribute>()
.PropertyName;
}
And call it like this:
var result = GetPropertyAttribute<myModel>(t => t.SomeString);
You can make this a bit more generic, for example:
public static TAttribute GetPropertyAttribute<TType, TAttribute>(Expression<Func<TType, object>> property)
where TAttribute : Attribute
{
var memberExpression = property.Body as MemberExpression;
if(memberExpression == null)
throw new ArgumentException("Expression must be a property");
return memberExpression.Member
.GetCustomAttribute<TAttribute>();
}
And now because the attribute is generic, you need to move the PropertyName
call outside:
var attribute = GetPropertyAttribute<myModel, JsonPropertyAttribute>(t => t.SomeString);
var result = attribute.PropertyName;