Custom Attribute in C#

public class MyCustomAttribute : Attribute
{
    public bool IgnoreIt { get; set; }
    public string FormatString { get; set; }
}

public class Student
{
    [MyCustom(FormatString = "hello", IgnoreIt = false)]
    public string Name { get; set; }

    [MyCustom(IgnoreIt = true)]
    public string Id { get; set; }
}

// Directly check for specific attribute (i.e. FormatString) in specific property 
// (i.e. Name)

var formatString = AttributeHelper.GetPropertyAttributeValue<Student, string, MyCustomAttribute, string>(prop => prop.Name, attr => attr.FormatString.ToString());

public static class AttributeHelper
{
    public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(
        Expression<Func<T, TOut>> propertyExpression,
        Func<TAttribute, TValue> valueSelector)
        where TAttribute : Attribute
    {
        var expression = (MemberExpression)propertyExpression.Body;
        var propertyInfo = (PropertyInfo)expression.Member;
        var att = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
        return att != null ? valueSelector(att) : default(TValue);
    }
}

//Dynamically check attribute and it's value
PropertyInfo[] props = typeof(Student).GetProperties();
foreach (PropertyInfo prop in props)
{
    var attribute = prop.GetCustomAttributes(typeof(MyCustomAttribute), true).FirstOrDefault() as MyCustomAttribute;
    if (attribute != null)
    {
        if (attribute.FormatString == null)
        {
            Console.WriteLine("null");
        }
        else
        {
            Console.WriteLine(attribute.FormatString);
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s