Custom Attributes in C#

Attributes are using to add information to Metadata. DotNet provides two types of attributes one is Custom and other is Pre-defined. The pre-defined Attribute AttributeUsage will help us to create new Attributes for classes .It contain few parameters like.

ValidON: Means which attributes can be placed. There is an enumeration for this, Default value is AttributeTargets.All.
AllowMultiple: This is used for activating multiple creation of the property. Default is single use.
Inherited: The parameter inherited (optional) provides value for the Inherited.

 The .Net Framework allows creation of custom attributes that can be used to store declarative information and can be retrieved at run-time. The below example helps to add the QC fix information’s to all methods, classes..
    [AttributeUsage(AttributeTargets.Class |
    AttributeTargets.Constructor |
    AttributeTargets.Field |
    AttributeTargets.Method |
    AttributeTargets.Property,
    AllowMultiple = true)]
    public class FixInfo : System.Attribute
    {
        private string qcNo;
        private string name_ofOwnr;
        private string dateofChage;
        public string description;
        public FixInfo(string bg, string dev, string d)
        {
            this.qcNo = bg;
            this.name_ofOwnr = dev;
            this.dateofChage = d;
        }
        public string QCNo
        {
            get
            {
                return qcNo;
            }
        }
        public string Owner
        {
            get
            {
                return name_ofOwnr;
            }
        }
        public string Date
        {
            get
            {
                return dateofChage;
            }
        }
        public string Description
        {
            get
            {
                return description;
            }
            set
            {
                description = value;
            }
        }
    }
}

The implementation of this Attribute like this.
[FixInfo("QCXXX1","Santhosh","01/12/2014", "Added additional Condition")]
[FixInfo("QCXX81", "Santhosh", "20/12/2014", "NUll value condition check added")]
        public void getmarks()
        {
            //.............
            ///Yourlogic
            /////...................
        }

 Happy doing....

No comments:

Post a Comment