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

Custom attribute in web.config

<configuration>
  <appSettings>
    	<add key="MyCustomAttribute" value="4" />
  </appSettings>
  <system.web>
  </system.web>
  <connectionStrings>        
  </connectionStrings>
</configuration>


Now access MyCustomAttribute from Controller

using System.Configuration;
ConfigurationManager.AppSettings["MyCustomAttribute "];


Get custom attribute value in c#

[MyAttribute(TableName="Persons")]
public class Person
{
    [MyAttribute(ColumnName="PersonId")]
    public int PersonId { get; set; }

    [MyAttribute(ColumnName = "PersonName")]
    public string PersonName { get; set; }
}


var person = new Person();

//Table name from Class Level attribute
MyAttribute TableAttribute = (MyAttribute)Attribute.GetCustomAttribute(person.GetType(), typeof(MyAttribute));

string tableName = TableAttribute.TableName;