Attribute in C# with Example

C#Attributes in DotNet are basically used to add declarative information to classes, properties, methods etc.  This declarative information can be retrieved using reflection at runtime.  An attribute is nothing more than a class which directly or indirectly inherits from Attribute class.  There are a lot of predefined attributes in DotNet framework.  However, you can also create your own custom attribute.  The attribute is added on top of type or type member inside a square bracket i.e. [AttributeName]

One of the predefined and commonly used attribute is Obsolete.  This attribute is basically applied to a method just to let a developer know, that this method is Obsolete and use another method.  An example of Obsolete attribute is given below.

using System;

namespace Hello_World
{

    class Program
    {
        static void Main(string[] args)
        {
            //This method will give warning while using it.
            OldFullName("Peter", "Todd");

            //Call to our new method.
            NewFullName("Albert", "Pinto");
        }

        //Obsolete Attribute with message as parameter.
        [Obsolete("This is method is Obsolete.  Please use NewFullName() method.")]
        public static void OldFullName(string first, string last)
        {
            Console.WriteLine("Full Name:  {0} {1}", first, last );
        }

        //New Method
        public static void NewFullName(string first, string last)
        {
            Console.WriteLine("Full Name:  {0} {1}", first, last);
        }
    }
}