Coupling properties with friendly names

Hey, For some time I've been looking for a good way to couple between the property, and it's display name.
Some may say it's a bad practice, but I think sometimes it has it's advantages.
So I solved it using DescriptionAttribute. The class is in System.dll, so we don't need to add any reference.
Let's take a look on the following class:
public class UserChecklistEntity
{
    public bool TakeTheTour { get; set; }

    public int VisitsCount { get; set; }
}
Let's decorate the properties with DescriptionAttributes:
public class UserChecklistEntity
{
    [Description("Take the tour")]
    public bool TakeTheTour { get; set; }

    [Description("Visits count")]
    public int VisitsCount { get; set; }
}
And now for the interesting part, add this extension method:
public static class ObjectExtensions
{
    public static string GetDescription<T>(this T obj, Expression<Func<T, object>> expression) where T : class
    {
        if (obj == null)
        {
            throw new ArgumentNullException("obj");
        }

        if (expression == null)
        {
            throw new ArgumentNullException("expression");
        }

        if (expression.NodeType == ExpressionType.Lambda && expression.Body is UnaryExpression)
        {
            var unaryExpression = (UnaryExpression)expression.Body;
            if (unaryExpression.Operand.NodeType == ExpressionType.MemberAccess && unaryExpression.Operand is MemberExpression)
            {
                var attribute = ((MemberExpression)unaryExpression.Operand).Member
                    .GetCustomAttributes(typeof(DescriptionAttribute), false)
                    .Select(x => x as DescriptionAttribute).FirstOrDefault() ?? new DescriptionAttribute();
                return attribute.Description;
            }
        }

        return null;
    }
}
For your convenience, because the extension method is on type object, put it in a non commonly used namespace.
The usage is very easy:
static void Main(string[] args)
{
    var userChecklistEntity = new UserChecklistEntity();
    var takeTheTourDescription = userChecklistEntity.GetDescription(x => x.TakeTheTour);
    var visitsCountDescription = userChecklistEntity.GetDescription(x => x.VisitsCount);

    Console.WriteLine(takeTheTourDescription);
    Console.WriteLine(visitsCountDescription);
}
Hope you find it useful!

Comments

Popular posts from this blog

Impersonating CurrentUser from SYSTEM

Add Styles & Scripts Dynamically to head tag in ASP .NET MVC

Json To Dictionary generic model binder