<p>What are attributes in .NET, what are they good for, and how do I create my own attributes?</p>

[{'answer_id': 20351, 'author': 'TheSmurf', 'author_id': 1975282, 'author_profile': 'https://Stackoverflow.com/users/1975282', 'pm_score': 3, 'selected': False, 'text': '<p>An attribute is a class that contains some bit of functionality that you can apply to objects in your code. To create one, create a class that inherits from System.Attribute.</p>\n\n<p>As for what they\'re good for... there are almost limitless uses for them.</p>\n\n<p><a href="http://www.codeproject.com/KB/cs/dotnetattributes.aspx" rel="noreferrer">http://www.codeproject.com/KB/cs/dotnetattributes.aspx</a></p>\n'}, {'answer_id': 20357, 'author': 'Stu', 'author_id': 414, 'author_profile': 'https://Stackoverflow.com/users/414', 'pm_score': 3, 'selected': False, 'text': '<p>Attributes are like metadata applied to classes, methods or assemblies.</p>\n\n<p>They are good for any number of things (debugger visualization, marking things as obsolete, marking things as serializable, the list is endless).</p>\n\n<p>Creating your own custom ones is easy as pie. Start here:</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/sw480ze8(VS.71).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/sw480ze8(VS.71).aspx</a></p>\n'}, {'answer_id': 20358, 'author': 'Chris Miller', 'author_id': 206, 'author_profile': 'https://Stackoverflow.com/users/206', 'pm_score': 2, 'selected': False, 'text': '<p>You can use custom attributes as a simple way to define tag values in sub classes without having to write the same code over and over again for each subclass.  I came across a nice <a href="http://blog.falafel.com/2008/04/15/CustomAttributesToTheRescue.aspx" rel="nofollow noreferrer">concise example by John Waters</a> of how to define and use custom attributes in your own code.</p>\n\n<p>There is a tutorial at <a href="http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx</a></p>\n'}, {'answer_id': 20418, 'author': 'Quibblesome', 'author_id': 1143, 'author_profile': 'https://Stackoverflow.com/users/1143', 'pm_score': 8, 'selected': True, 'text': '<p>Metadata. Data about your objects/methods/properties. </p>\n\n<p>For example I might declare an Attribute called: DisplayOrder so I can easily control in what order properties should appear in the UI. I could then append it to a class and write some GUI components that extract the attributes and order the UI elements appropriately.</p>\n\n<pre><code>public class DisplayWrapper\n{\n    private UnderlyingClass underlyingObject;\n\n    public DisplayWrapper(UnderlyingClass u)\n    {\n        underlyingObject = u;\n    }\n\n    [DisplayOrder(1)]\n    public int SomeInt\n    {\n        get\n        {\n            return underlyingObject .SomeInt;\n        }\n    }\n\n    [DisplayOrder(2)]\n    public DateTime SomeDate\n    {\n        get\n        {\n            return underlyingObject .SomeDate;\n        }\n    }\n}\n</code></pre>\n\n<p>Thereby ensuring that SomeInt is always displayed before SomeDate when working with my custom GUI components.</p>\n\n<p>However, you\'ll see them most commonly used outside of the direct coding environment. For example the Windows Designer uses them extensively so it knows how to deal with custom made objects. Using the BrowsableAttribute like so:</p>\n\n<pre><code>[Browsable(false)]\npublic SomeCustomType DontShowThisInTheDesigner\n{\n    get{/*do something*/}\n}\n</code></pre>\n\n<p>Tells the designer not to list this in the available properties in the Properties window at design time for example.</p>\n\n<p>You <em>could</em> also use them for code-generation, pre-compile operations (such as Post-Sharp)  or run-time operations such as Reflection.Emit.\nFor example, you could write a bit of code for profiling that transparently wrapped every single call your code makes and times it. You could "opt-out" of the timing via an attribute that you place on particular methods.</p>\n\n<pre><code>public void SomeProfilingMethod(MethodInfo targetMethod, object target, params object[] args)\n{\n    bool time = true;\n    foreach (Attribute a in target.GetCustomAttributes())\n    {\n        if (a.GetType() is NoTimingAttribute)\n        {\n            time = false;\n            break;\n        }\n    }\n    if (time)\n    {\n        StopWatch stopWatch = new StopWatch();\n        stopWatch.Start();\n        targetMethod.Invoke(target, args);\n        stopWatch.Stop();\n        HandleTimingOutput(targetMethod, stopWatch.Duration);\n    }\n    else\n    {\n        targetMethod.Invoke(target, args);\n    }\n}\n</code></pre>\n\n<p>Declaring them is easy, just make a class that inherits from Attribute. </p>\n\n<pre><code>public class DisplayOrderAttribute : Attribute\n{\n    private int order;\n\n    public DisplayOrderAttribute(int order)\n    {\n        this.order = order;\n    }\n\n    public int Order\n    {\n        get { return order; }\n    }\n}\n</code></pre>\n\n<p>And remember that when you use the attribute you can omit the suffix "attribute" the compiler will add that for you.</p>\n\n<p><strong>NOTE:</strong> Attributes don\'t do anything by themselves - there needs to be some other code that uses them. Sometimes that code has been written for you but sometimes you have to write it yourself. For example, the C# compiler cares about some and certain frameworks frameworks use some (e.g. NUnit looks for [TestFixture] on a class and [Test] on a test method when loading an assembly).<br>\nSo when creating your own custom attribute be aware that it will not impact the behaviour of your code at all. You\'ll need to write the other part that checks attributes (via reflection) and act on them. </p>\n'}, {'answer_id': 20455, 'author': 'Patrik Svensson', 'author_id': 936, 'author_profile': 'https://Stackoverflow.com/users/936', 'pm_score': 4, 'selected': False, 'text': '<p>Attributes are a kind of meta data for tagging classes. This is often used in WinForms for example to hide controls from the toolbar, but can be implemented in your own application to enable instances of different classes to behave in specific ways. </p>\n\n<p>Start by creating an attribute:</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)]\npublic class SortOrderAttribute : Attribute\n{\n    public int SortOrder { get; set; }\n\n    public SortOrderAttribute(int sortOrder)\n    {\n        this.SortOrder = sortOrder;\n    }\n}\n</code></pre>\n\n<p>All attribute classes must have the suffix "Attribute" to be valid.<br>\nAfter this is done, create a class that uses the attribute.</p>\n\n<pre><code>[SortOrder(23)]\npublic class MyClass\n{\n    public MyClass()\n    {\n    }\n}\n</code></pre>\n\n<p>Now you can check a specific class\' <code>SortOrderAttribute</code> (if it has one) by doing the following:</p>\n\n<pre><code>public class MyInvestigatorClass\n{\n    public void InvestigateTheAttribute()\n    {\n        // Get the type object for the class that is using\n        // the attribute.\n        Type type = typeof(MyClass);\n\n        // Get all custom attributes for the type.\n        object[] attributes = type.GetCustomAttributes(\n            typeof(SortOrderAttribute), true);\n\n        // Now let\'s make sure that we got at least one attribute.\n        if (attributes != null &amp;&amp; attributes.Length &gt; 0)\n        {\n            // Get the first attribute in the list of custom attributes\n            // that is of the type "SortOrderAttribute". This should only\n            // be one since we said "AllowMultiple=false".\n            SortOrderAttribute attribute = \n                attributes[0] as SortOrderAttribute;\n\n            // Now we can get the sort order for the class "MyClass".\n            int sortOrder = attribute.SortOrder;\n        }\n    }\n}\n</code></pre>\n\n<p>If you want to read more about this you can always check out <a href="http://msdn.microsoft.com/en-us/library/aa288059.aspx" rel="nofollow noreferrer">MSDN</a> which has a pretty good description.<br>\nI hope this helped you out!</p>\n'}, {'answer_id': 20482, 'author': 'denis phillips', 'author_id': 748, 'author_profile': 'https://Stackoverflow.com/users/748', 'pm_score': 2, 'selected': False, 'text': '<p>As said, Attributes are relatively easy to create. The other part of the work is creating code that uses it. In most cases you will use reflection at runtime to alter behavior based on the presence of an attribute or its properties. There are also scenarios where you will inspect attributes on compiled code to do some sort of static analysis. For example, parameters might be marked as non-null and the analysis tool can use this as a hint.</p>\n\n<p>Using the attributes and knowing the appropriate scenarios for their use is the bulk of the work.</p>\n'}, {'answer_id': 20508, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 3, 'selected': False, 'text': '<p>In the project I\'m currently working on, there is a set of UI objects of various flavours and an editor to assembly these objects to create pages for use in the main application, a bit like the form designer in DevStudio. These objects exist in their own assembly and each object is a class derived from <code>UserControl</code> and has a custom attribute. This attribute is defined like this:</p>\n\n<pre><code>[AttributeUsage (AttributeTargets::Class)]\npublic ref class ControlDescriptionAttribute : Attribute\n{\npublic:\n  ControlDescriptionAttribute (String ^name, String ^description) :\n    _name (name),\n    _description (description)\n  {\n  }\n\n  property String ^Name\n  {\n    String ^get () { return _name; }\n  }\n\n  property String ^Description\n  {\n    String ^get () { return _description; }\n  }\n\nprivate:\n  String\n    ^ _name,\n    ^ _description;\n};\n</code></pre>\n\n<p>and I apply it to a class like this:</p>\n\n<pre><code>[ControlDescription ("Pie Chart", "Displays a pie chart")]\npublic ref class PieControl sealed : UserControl\n{\n  // stuff\n};\n</code></pre>\n\n<p>which is what the previous posters have said.</p>\n\n<p>To use the attribute, the editor has a <code>Generic::List &lt;Type&gt;</code> containing the control types. There is a list box which the user can drag from and drop onto the page to create an instance of the control. To populate the list box, I get the <code>ControlDescriptionAttribute</code> for the control and fill out an entry in the list:</p>\n\n<pre><code>// done for each control type\narray &lt;Object ^&gt;\n  // get all the custom attributes\n  ^attributes = controltype-&gt;GetCustomAttributes (true);\n\nType\n  // this is the one we\'re interested in\n  ^attributetype = ECMMainPageDisplay::ControlDescriptionAttribute::typeid;\n\n// iterate over the custom attributes\nfor each (Object ^attribute in attributes)\n{\n  if (attributetype-&gt;IsInstanceOfType (attribute))\n  {\n    ECMMainPageDisplay::ControlDescriptionAttribute\n      ^description = safe_cast &lt;ECMMainPageDisplay::ControlDescriptionAttribute ^&gt; (attribute);\n\n    // get the name and description and create an entry in the list\n    ListViewItem\n      ^item = gcnew ListViewItem (description-&gt;Name);\n\n    item-&gt;Tag = controltype-&gt;Name;\n    item-&gt;SubItems-&gt;Add (description-&gt;Description);\n\n    mcontrols-&gt;Items-&gt;Add (item);\n    break;\n  }\n}\n</code></pre>\n\n<p>Note: the above is C++/CLI but it\'s not difficult to convert to C#\n(yeah, I know, C++/CLI is an abomination but it\'s what I have to work with :-( )</p>\n\n<p>You can put attributes on most things and there are whole range of predefined attributes. The editor mentioned above also looks for custom attributes on properties that describe the property and how to edit it.</p>\n\n<p>Once you get the whole idea, you\'ll wonder how you ever lived without them.</p>\n'}, {'answer_id': 20665, 'author': 'urini', 'author_id': 373, 'author_profile': 'https://Stackoverflow.com/users/373', 'pm_score': 2, 'selected': False, 'text': '<p>Attributes are, essentially, bits of data you want to attach to your <strong>types</strong> (classes, methods, events, enums, etc.)</p>\n\n<p>The idea is that at run time some other type/framework/tool will query <strong>your</strong> type for the information in the attribute and act upon it.</p>\n\n<p>So, for example, Visual Studio can query the attributes on a 3rd party control to figure out which properties of the control should appear in the Properties pane at design time.</p>\n\n<p>Attributes can also be used in Aspect Oriented Programming to inject/manipulate objects at run time based on the attributes that decorate them and add validation, logging, etc. to the objects without affecting the business logic of the object.</p>\n'}, {'answer_id': 394559, 'author': 'Jay Bazuzi', 'author_id': 5314, 'author_profile': 'https://Stackoverflow.com/users/5314', 'pm_score': 2, 'selected': False, 'text': '<p>To get started creating an attribute, open a C# source file, type <code>attribute</code> and hit [TAB].  It will expand to a template for a new attribute.</p>\n'}, {'answer_id': 554006, 'author': 'Drew Noakes', 'author_id': 24874, 'author_profile': 'https://Stackoverflow.com/users/24874', 'pm_score': 5, 'selected': False, 'text': '<p>Many people have answered but no one has mentioned this so far...</p>\n\n<p>Attributes are used heavily with reflection.  Reflection is already pretty slow.</p>\n\n<p>It is <em>very worthwhile</em> marking your custom attributes as being <code>sealed</code> classes to improve their runtime performance.</p>\n\n<p>It is also a good idea to consider where it would be appropriate to use place such an attribute, and to attribute your attribute (!) to indicate this via <a href="http://msdn.microsoft.com/en-us/library/system.attributeusageattribute.aspx" rel="noreferrer"><code>AttributeUsage</code></a>.  The list of available attribute usages might surprise you:</p>\n\n<ul>\n<li>Assembly</li>\n<li>Module</li>\n<li>Class</li>\n<li>Struct</li>\n<li>Enum</li>\n<li>Constructor</li>\n<li>Method</li>\n<li>Property</li>\n<li>Field</li>\n<li>Event</li>\n<li>Interface</li>\n<li>Parameter</li>\n<li>Delegate </li>\n<li>ReturnValue</li>\n<li>GenericParameter</li>\n<li>All</li>\n</ul>\n\n<p>It\'s also cool that the AttributeUsage attribute is part of the AttributeUsage attribute\'s signature.  Whoa for circular dependencies!</p>\n\n<pre><code>[AttributeUsageAttribute(AttributeTargets.Class, Inherited = true)]\npublic sealed class AttributeUsageAttribute : Attribute\n</code></pre>\n'}, {'answer_id': 1603356, 'author': 'Josh G', 'author_id': 64329, 'author_profile': 'https://Stackoverflow.com/users/64329', 'pm_score': 1, 'selected': False, 'text': '<p>Attributes are also commonly used for Aspect Oriented Programming. For an example of this check out the <a href="http://www.postsharp.org" rel="nofollow noreferrer">PostSharp</a> project.</p>\n'}]
['https://Stackoverflow.com/questions/20346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1595/']