Home > DeveloperSection > Beginner > Attributes in c#

Attributes in c#


.NET C#  ASP.Net 
Ratings:
0 Comment(s)
 1379  View(s)
Rate this:

Attributes in c#

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

{

  class Program

    {

#if DEBUG

        static int testCounter=0;

#endif

//Condition attribute

        [Conditional("DEBUG")]

        static void someTestMethod(int i)

        {

            Console.Write(i);

        }

static void 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 class Operation

    {

//Custom attribute

//Call MyToken Constructor

        [MyToken("Operation 1")]

        public static string operation1()

        {

            return "Hey, I'm  operation1";

        }

         [MyToken("Operation 2")]

        public static string operation2()

        {

            return "Hey, I'm  operation2";

        }

    }

}

Create Default.aspx

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

 

<!DOCTYPE html>

 

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

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

        <table>

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

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

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

        </table>

       

        <asp:Label ID="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

{

    public partial class Default : System.Web.UI.Page

    {

        void Populatedata()

        {

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

            MyToken token = null;

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

            foreach (MethodInfo method in methods)

            {

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

                if (token == null)

                    continue;

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

            }

            DropDownList1.DataSource = items;

            DropDownList1.DataTextField = "Key";

            DropDownList1.DataValueField = "Value";

            DropDownList1.DataBind();

        }

        protected void Page_Load(object sender, EventArgs e)

        {

            if(!IsPostBack)

            Populatedata();

 

        }

 

        protected void 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:

 


Don't want to miss updates? Please click the below button!

Follow MindStick