I have the following class structure:
MyAttribute.cs
public sealed class MyAttribute : Attribute
{
public MyAttribute(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));
}
Name = name;
}
public string Name { get; }
}
Matrix.cs
public class Matrix
{
[MyAttribute("awesome_name")]
public string AwesomeName { get; set; }
}
And we make an method to "extract" the value defined on name
of MyAttribute
:
AttributeExtensions.cs
public static class AttributeExtensions
{
public static string GetMyAttributeNameOfProperty<TClass>(Expression<Func<TClass, object>> expression)
{
if (expression.Body is MemberExpression memberExpression)
{
var propertyInfo = (PropertyInfo)memberExpression.Member;
var hasMyAttribute = propertyInfo.IsDefined(typeof(MyAttribute), false);
if (hasMyAttribute)
{
return propertyInfo.GetCustomAttribute<MyAttribute>().Name;
}
}
return default;
}
}
Finally, we call this way:
AttributeExtensions.GetMyAttributeNameOfProperty<Matrix>(exp => exp.AwesomeName)
This call, returns: "awesome_name"
We have some doubts:
Exists an more "clean" way to pass the property of
<TClass>(exp.AwesomeName)
to this extension method?We really need of
Expression<>
? It's possible to make this only withFunc<TClass, object>
?
Like:
GetMyAttributeNameOfProperty<TClass>(Func<TClass, object> expression)
Any suggestions?
AttributeExtensions.GetMyAttributeNameOfProperty<Matrix>(exp => exp.AwesomeName)"
Please, don't vote down! This is an solution and fully works! \$\endgroup\$