---
title: "Attributes in c#"  
description: "In this article, I’m explaining about attributes in C#"  
author: "priyanka kushwaha"  
published: 2015-03-03  
updated: 2019-09-07  
canonical: https://www.mindstick.com/articles/1622/attributes-in-c-sharp  
category: ".net"  
tags: ["c#", "asp.net"]  
reading_time: 3 minutes  

---

# Attributes in c#

In this article, I’m explaining about [attributes](https://www.mindstick.com/articles/13105/2-attributes-that-make-your-odoo-ecommerce-theme-productive-and-engaging) in C#

Attributes are classes which are derived from the **System.Attributes** class which is an [abstract class](https://www.mindstick.com/articles/1430/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](https://www.mindstick.com/forum/161622/how-do-you-determine-whether-a-file-is-locked-or-in-use-by-another-process) 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](https://www.mindstick.com/interview/358/which-is-the-first-level-of-compilation-in-the-dot-net-languages) 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](https://answers.mindstick.com/qa/30915/explain-the-reason-that-why-big-tyres-are-used-in-rear-of-vehicles) why the type is obsolete [as well as](https://www.mindstick.com/forum/156547/difference-between-max-width-and-width-as-well-as-max-height-and-height) 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](https://www.mindstick.com/articles/12824/calculator-application-in-android) need.

## Creating and using custom attributes involve four steps:

1. Declaring a custom attributes

2. Constructing the custom attributes

3. Apply the [custom attribute](https://www.mindstick.com/interview/492/how-do-you-specify-a-custom-attribute-for-the-entire-assembly-rather-than-for-a-class) on a target program element.

4. Accessing attributes through [reflection](https://www.mindstick.com/articles/13004/how-to-write-a-reflection-paper)

## 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](https://www.mindstick.com/news/2675/bmw-agrees-to-integrate-blockchain-with-operations-partners-with-bnb-chain-coinweb).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:**

![Attributes in c#](https://www.mindstick.com/mindstickarticle/755e77df-263b-4633-9b47-2c413fe8a187/images/02e37722-b361-49ca-86f3-cbfa35f73960.png)

![Attributes in c#](https://www.mindstick.com/mindstickarticle/755e77df-263b-4633-9b47-2c413fe8a187/images/077372c7-d7f2-47c8-b300-88ef8ea2a59f.png)

---

Original Source: https://www.mindstick.com/articles/1622/attributes-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
