Click here to Skip to main content
15,885,921 members
Articles / Operating Systems / Windows
Article

Custom Attributes in .NET

Rate me:
Please Sign up or sign in to vote.
2.28/5 (15 votes)
11 Oct 20064 min read 46.9K   17   5
How custom attributes are used in .NET

Introduction

Attributing is attaching declarative information to various programming entities and retrieving this at run-time. A program can specify the accessibility of a method in a class by specifying it with some access modifiers like private, public etc.<o:p>

Where as the declarative information can be attached by defining and using attributes. <o:p>

          Custom attributing is nothing but a way to find out new attributes which is very requirement specific.<o:p>

          One of the most powerful aspects of .NET Framework is its support for attributes. Before .NET framework, Microsoft supported attributes in Microsoft Transaction Services (MTS) and COM+. These runtime supported a handful of attributes where as .NET has got scores of attributes already defined in the Framework Class library. Also extensibility in this regard allows the programmer to create their own attributes known as custom attributes. <o:p>

          I’ll cover the .NET support for attributes and custom attributes in this article keeping C# as the language for demonstration.<o:p>

<o:p> 

Attribute Programming:<o:p>

          We’ll go with ‘Attribute’ first to understand the basic. Then we’ll try to learn how to create and use Custom Attribute.<o:p>

          Convention of the attribute classes in .NET will have suffix ‘Attribute’. .NET compilers will compile Serializable and SerializableAttribute both. These are the pre-defined attributes in the Framework. Suppose I’m using a attribute which is applicable to Assembly level. In my example, in AssemblyInfo.cs I’ve written a description ("Arindam's Attribute test assembly") in AssemblyDescription which in turn can be checked in the metadata of the assembly as figure1. Image 1

                                      Figure-1

So this information can be retrieved at run-time by boring into the metadata using Reflection. I’ll come to this later when Custom attribute will come.<o:p>

Now I’ve added a class named SerializableClass.cs (figure-2). Only by using the Searilizable attribute to the class SerializableClass, I specify that this class can be serialized with default serialization features provided in .NET framework. This does not require any extra coding. So one of the most achieved features of attribute programming is to reduce unnecessary coding or reusability.

Sample screenshot

                                             Figure-2

As per the above class the strNonSerializable is not a serializable one. So far we can see the use of pre defined attributes. Now we’ll look into the more details.<o:p>

<o:p> 

Custom Attribute:<o:p>

          We’ll directly get into the creation of a custom attribute class. A custom attribute will inherit from Attribute class which is present in .NET framework. This is an abstract base class. Any custom or pre-defined attribute must inherit from this class.

Sample screenshot

                                   Figure-3

I’ll create an attribute (AuthorAttribute) which will cater as an author of a programming entity. This attribute class (figure-3) will have the AuthorName and CreationDate. There’re four sections in a custom attribute:<o:p>

·         AttributeUsage<o:p>

This has three members – AttributeTarget, Inherited and AllowMultiple.<o:p>

In my AuthorAttribute class AttributeTarget is All. AttributeTarget is an enumeration. This has got values like All, Class, Method, Assembly, Enum etc. AttributeTarget specifies that the Attribute can be used to which programming entity. An Attribute can have multiple AttributeTarget separated by ‘|’. If Inherited is set to true then the Attribute gets attached to the sub classes of the class where it’s used. For my AuthorAttribute this Inherited is set to true. So wherever this attribute will be used the following sub classes will be able use this AuthorAttribute too. AllowMultiple denotes whether the Attribute can be used multiple times in the target element.<o:p>

For my example this is set to true. So if you use this in a class then you can use it in a method of that class too.<o:p>

·         Class Declaration<o:p>

Custom Attribute should inherit System.Attribute and access modifier should be public.<o:p>

·         Constructor<o:p>

This is like the other classes. Parameters can be passed to the Attribute class. An Attribute can have multiple constructors.<o:p>

·         Properties<o:p>

This is also same thing as we use Properties in other classes. In my example I’ve created two Properties AuthorName and CreationDate.<o:p>

Using AuthorAttribute:<o:p>

          Here I’ve provided the code snippet (Figure-5) that’ll show how to use the AuthorAttribute which is a Custom Attribute. You can see in the code snippet I’ve used the AuthorAttribute to the MyClass as well as to the Main method. I showed the details used at class level leaving the method level to the readers. In the following you can get the output in Figure-4.

Sample screenshot

Sample screenshot

                                                Figure-5

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
India India
I have been working in IT industry for the last 6 years.
My comfort zone is .NET and Microsoft technologies.

Comments and Discussions

 
Questiongood starting point Pin
Southmountain1-Jul-22 7:30
Southmountain1-Jul-22 7:30 
GeneralMy vote of 3 Pin
NoCodeMonkey19-Apr-12 16:44
NoCodeMonkey19-Apr-12 16:44 
GeneralMy vote of 2 Pin
Rob Graham15-Dec-08 14:47
Rob Graham15-Dec-08 14:47 
GeneralNice work can u tell me one think Pin
wasimsharp10-Aug-08 20:44
wasimsharp10-Aug-08 20:44 
GeneralSource code missing. Pin
TBermudez12-Oct-06 10:59
TBermudez12-Oct-06 10:59 
The link is broken.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.