articles

Home / DeveloperSection / Articles / Attributes in c#

Attributes in c#

priyanka kushwaha5061 03-Mar-2015

In this article, I’m explaining about attributes in C#

 

Attributes are classes which are derived from the System.Attributes class which is an abstract class. There are lot of different attributes provided by the framework for different functionality. We can create more attributes by deriving from the Attributes class if required. Some of the attributes provided by the framework are as follows:

Conditional:This is used with methods and used to determine whether should execute. So if we attach the following attribute with a method then a method will execute for a debug build but not for the release build.

 

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Diagnostics;

namespace conditionalApplication

{

  classProgram

    {

#if DEBUG

        staticint testCounter=0;

#endif

//Condition attribute

        [Conditional("DEBUG")]

        staticvoid someTestMethod(int i)

        {

            Console.Write(i);

        }

staticvoid Main(string[] args)

        {

            someTestMethod(testCounter+1);

            MethodA();

            Console.ReadKey();

        }

    }

}

 

 

Obsolete:Obsolete attributes are used to display an error or warning during compilation with an optional message to alert the developer that the given type or its member should not be used in the code as it is going to be replaced. The displayed message can also explain the reason why the type is obsolete as well as provide an alternative.

Example:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Diagnostics;

namespace conditionalApplication

{

class Program

    {

//Obsolete attribute

[Obsolete("use method instead")]

        static void MethodA()

        {

            Console.Write("Hello");

        }

     static void Main(string[] args)

        {

            MethodA();

            Console.ReadKey();

        }

    }

}

 

Create Custom Attributes

The .net Framework allows to create custom attributes that can be used to store declarative information and can be retrieved at run-time. This information can be related to any target element depending upon the design criteria and application need.

Creating and using custom attributes involve four steps:

1.       Declaring a custom  attributes

2.       Constructing the custom attributes

3.       Apply the custom attribute on a target program element.

4.       Accessing attributes through reflection

Example:

Create MyToken.cs Class

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace CustomAttributeExample

{

    public class MyToken:Attribute

    {

        public string Display { get; set; }

        public MyToken(string dn)

        {

            Display = dn;

        }

    }

 

Create Operations.cs class

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace CustomAttributeExample

{

    public classOperation

    {

//Custom attribute

//Call MyToken Constructor

        [MyToken("Operation 1")]

        publicstaticstring operation1()

        {

            return"Hey, I'm  operation1";

        }

         [MyToken("Operation 2")]

        publicstaticstring operation2()

        {

            return"Hey, I'm  operation2";

        }

    }

}

Create Default.aspx

<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="CustomAttributeExample.Default"%>

 

<!DOCTYPEhtml>

 

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

    <title></title>

</head>

<body>

    <formid="form1"runat="server">

        <table>

            <tr><td>Select Operations</td><td><asp:DropDownListID="DropDownList1"runat="server"></asp:DropDownList></td></tr>

            <tr><td></td><td>

                <asp:ButtonID="btnExe"runat="server"Text="Execute"OnClick="btnExe_Click"/></td></tr>

        </table>

       

        <asp:LabelID="lblmsg"runat="server"Text=""></asp:Label>

    </form>

</body>

</html>

 

Write in Default.aspx.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Reflection;

namespace CustomAttributeExample

{

    publicpartialclassDefault : System.Web.UI.Page

    {

        void Populatedata()

        {

            MethodInfo[] methods = typeof(Operation).GetMethods();

            MyToken token = null;

            List<KeyValuePair<string, MethodInfo>> items = newList<KeyValuePair<string, MethodInfo>>();

            foreach (MethodInfo method in methods)

            {

                token = Attribute.GetCustomAttribute(method, typeof(MyToken), false) asMyToken;

                if (token == null)

                    continue;

         items.Add(newKeyValuePair<string, MethodInfo>(token.Display, method));

            }

            DropDownList1.DataSource = items;

            DropDownList1.DataTextField = "Key";

            DropDownList1.DataValueField = "Value";

            DropDownList1.DataBind();

        }

        protectedvoid Page_Load(object sender, EventArgs e)

        {

            if(!IsPostBack)

            Populatedata();

 

        }

 

        protectedvoid btnExe_Click(object sender, EventArgs e)

        {

            if (DropDownList1.SelectedIndex< 0)

                return;

            string str;

            int method = DropDownList1.SelectedIndex;

            if (method == 0)

                str= Operation.operation1();

            else

                str=Operation.operation2();

            lblmsg.Text = str;

        }

    }

}

 

Output:

 

Attributes in c#

Attributes in c#

Updated 07-Sep-2019

Leave Comment

Comments

Liked By