C# Attributes

 

In C# attributes are used to provide the information about specific class or any member in the class. Through attributes we can provide the information design-level information and run-time information. In this article we discuss about how to use predefined attributes and how to create our own custom attributes.

 

For example you developed a class with specific method with some functionality some time back. Later point of time you felt like that method is not fulfilling all functional requirements, so you have to create new method or you have to  do changes for existing method. But doing changes for existing method is not preferred way because already some clients are using that method. So you have to create the new method, but you have to force the new users to use new method not old method. So in this type of situation we have to provide some information or we have to give compile-time error if client is using old method as shown below.

 

 

using System;

 

namespace CSharpAttributes

{

    class Program

    {

        static void Main(string[] args)

        {

            GetEmpDataById();

        }

 

        [Obsolete("this is old method, use new method instead", true)]

        static void GetEmpDataById()

        {

       

        }

 

    }

}

 

As shown above we are using attribute Obsolete which provides the information like specific method is obsolete to use. It takes two parameters one is information for user and another parameter is boolean. If this boolean variable is false it provides only information not any error whenever it is called as shown below.

 

 

 

If the boolean variable is true, run-time error generates whenever the specific method is called as shown below.

 

 

In my next article I will explain about how to create Custom Attributes in C#.