A good question would be, how do you pass a property in a type-safe way. Properties are not first-class objects in .NET.
One of the ways would be this:
using System.Linq.Expressions;
// ...
static string GetJsonPropertyName<TC, TP>(Expression<Func<TC, TP>> expr)
{
if (expr.Body is MemberExpression body)
return body.Member.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName;
else
throw new ArgumentException("expect field access lambda");
}
You'll need to call the function like this:
var jsonName = GetJsonPropertyName<SampleClass, string>(x => x.SampleClassID);
Yes, it doesn't feel very natural. Sorry for that.
Thanks to @elgonzo, the code can be simplified like this:
static string GetJsonPropertyName<TC>(Expression<Func<TC, object>> expr)
{
// in case the property type is a value type, the expression contains
// an outer Convert, so we need to remove it
var body = (expr.Body is UnaryExpression unary) ? unary.Operand : expr.Body;
if (body is System.Linq.Expressions.MemberExpression memberEx)
return memberEx.Member.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName;
else
throw new ArgumentException("expect field access lambda");
}
var jsonName = GetJsonPropertyName<SampleClass>(x => x.SampleClassID);