Click here to Skip to main content
13,143,708 members (28,826 online)
Click here to Skip to main content
Add your own
alternative version

Stats

151.2K views
145 bookmarked
Posted 8 Oct 2014

C# Attributes in 5 minutes

, 19 Oct 2014
Rate this:
Please Sign up or sign in to vote.
In this article we will try to understand C# Attributes.

What are attributes and why do we need it?

How can we create custom Attributes?

Is it possible to restrict a custom attribute to a method only?

Other than information what more can we do?

Do attributes get inherited ?

What if we want some attributes to be prevented from inheriting?

If I want an attribute to be used only once in a program?

What are attributes and why do we need it?

“Attribute is nothing but a piece of information”.

This information can be attached to your method, class, namespace, assembly etc. Attributes are part of your code this makes developers life easier as he can see the information right upfront in the code while he is calling the method or accessing the class and take actions accordingly.

For instance below is a simple class where “Method1” is decorated by the “Obsolete” attribute. Attributes are defined by using the “[]“ symbol. So when developers starting coding in this class they are alerted that“Method1” is obsolete and code should be now written in “NewMethod1”.

public class Class1
{
        [Obsolete]
        public void Method1()
        {
        }
        public void NewMethod1()
        {
        }
}

In the same way if somebody is trying to create objectof “Class1” he gets an alert in the tool tip as shown in the below code snippet that “Method1” is obsolete and he should use “NewMethod1”.

So in short Attributes are nothing small piece of information which is embedded declaratively in the code itself which developers can see upfront.

In case you want to show some message to the developers you can pass the message in the “Obsolete” attribute as shown in the below code snippet.

[Obsolete("Please use NewMethod1")]
public void Method1()
{

}

If you want to be bit strict and do not want developers to use that method, you can pass ‘true” to the “Obsolete” attribute as shown in the below code.

[Obsolete("Please use NewMethod1",true)]
public void Method1()
{

}

Now in case developer tries to make a call to “Method1” they will get error and not just a simple warning.

How can we create custom Attributes?

The “Obsolete” attribute which we discussed at the top is a readymade attribute To create a custom attributes you need to inherit from the attribute class. Below is a simple “HelpAttribute” which has a “HelpText” property.

class HelpAttribute : Attribute
{
public string HelpText { get; set; }

}

“HelpAttribute” is applied to the “Customer” as shown in the code below. Now developers who see this class , see the information right in the front of their eyes.

[Help(HelpText="This is a class")]
class Customer
{
private string _CustomerCode;

[Help(HelpText = "This is a property")]
public string CustomerCode
        {
get { return _CustomerCode; }
set { _CustomerCode = value; }
        }

        [Help(HelpText = "This is a method")]
public void Add()
        {
        }
    }

Is it possible to restrict a custom attribute to a method only?

By using the “AttributeUsage” and “AttributeTargets” you can restrict the attribute to a particular section like class , method , property etc. Below is a simple custom attribute is now confined only to methods.

[AttributeUsage(AttributeTargets.Method)]
class HelpAttribute : Attribute
{
        public string HelpText { get; set; }

}

If you try to apply the above attribute over a class or property you would get a compile time error as shown below.

You can also restrict attribute's to a class , constructor , assembly etc. Below is the list of possibilities to which you can confine your attribute.

Other than information what more can we do?

One use which we have discussed till now is for the developer’s that they can see the information while coding and take decision accordingly. Other use is you can read the information programmatically using reflection and act on it.

For instance below is a custom attribute which describes length of characters for a property of a class.

[AttributeUsage(AttributeTargets.Property)]
class Check : Attribute
{
        public int MaxLength { get; set; }
}

Below is a customer class over which that property is decorated providing information that the maximum length of “CustomerCode” property cannot exceed 10 character.

class Customer
    {
private string _CustomerCode;

        [Check(MaxLength = 10)]
public string CustomerCode
        {
get { return _CustomerCode; }
set { _CustomerCode = value; }
        }        
    }

Below goes the code which will loop dynamically through the attributes of each property and do the length validation check.

So the first step is to create the object of the customer class.

// Create the object of Customer class
// and load it with some data
Customer obj = new Customer();
obj.CustomerCode = "12345678901";

Second step is to get the “Type” of the object. Because once we get the type of the object we can browse properties, methods etc of the object.

// Get the type of the object
Type objtype = obj.GetType();

Use the “Type” object and loop through all properties and attributes of those properties.

// Loop through all properties
foreach (PropertyInfo p in objtype.GetProperties())
{
        // for every property loop through all attributes
        foreach (Attribute a in p.GetCustomAttributes(false))
        {
  }
}

Once you get hold of the attribute you can do the length check and raise exception accordingly.

// Loop through all properties
foreach (PropertyInfo p in objtype.GetProperties())
{
        // for every property loop through all attributes
        foreach (Attribute a in p.GetCustomAttributes(false))
        {
                    Check c = (Check)a;
if (p.Name == "CustomerCode")
                    {
                   // Do the length check and and raise exception accordingly
if (obj.CustomerCode.Length > c.MaxLength)
                        {
throw new Exception(" Max length issues ");
                        }
                    }
                }
            }

Do attributes get inherited ?

Yes, they get inherited in the child classes.

What if we want some attributes to be prevented from inheriting?

We have an “Inherited” property in “AttributeUsage” if we set it to false those attributes will not be inherited in the child classes.

[AttributeUsage(AttributeTargets.Property,Inherited=false)]
class Check : Attribute
{
publicintMaxLength { get; set; }  
}

If I want an attribute to be used only once in a program?

If you specify “AllowMultiple” as true it can be used multiple times in the same program.

[AttributeUsage(AttributeTargets.Property,AllowMultiple=false)]
class Check : Attribute
{
public int MaxLength { get; set; }

}

See the below facebook video which explains and demonstrates C# Attributes practically.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


You may also be interested in...

Comments and Discussions

 
GeneralGreat Article Pin
wwwx27-Apr-17 2:39
memberwwwx27-Apr-17 2:39 
QuestionGetType() and Types inside Types Pin
Member 123074274-Feb-16 4:16
memberMember 123074274-Feb-16 4:16 
Question5 star Pin
israelfh20-Sep-15 3:42
memberisraelfh20-Sep-15 3:42 
General5 Star Pin
manoharmind6-Jul-15 19:27
membermanoharmind6-Jul-15 19:27 
QuestionIf you specify “AllowMultiple” as true it can be used multiple times in the same program. Pin
Duncan Edwards Jones27-Mar-15 0:02
professionalDuncan Edwards Jones27-Mar-15 0:02 
AnswerRe: If you specify “AllowMultiple” as true it can be used multiple times in the same program. Pin
Shashank Bisen7-Aug-15 22:40
memberShashank Bisen7-Aug-15 22:40 
GeneralMy vote of 5 Pin
Bruno Sprecher14-Jan-15 8:18
professionalBruno Sprecher14-Jan-15 8:18 
Generalnice Pin
AJSON16-Nov-14 6:35
mentorAJSON16-Nov-14 6:35 
GeneralMy vote of 5 Pin
Renju Vinod10-Nov-14 17:12
professionalRenju Vinod10-Nov-14 17:12 
QuestionNice Article Sir. How can I get inbuilt attribute list ? Pin
koolprasad200319-Oct-14 21:11
memberkoolprasad200319-Oct-14 21:11 
BugSome typos / mistakes Pin
_Noctis_18-Oct-14 0:35
professional_Noctis_18-Oct-14 0:35 
GeneralRe: Some typos / mistakes Pin
Afzaal Ahmad Zeeshan18-Oct-14 22:23
professionalAfzaal Ahmad Zeeshan18-Oct-14 22:23 
GeneralRe: Some typos / mistakes Pin
_Noctis_19-Oct-14 0:09
professional_Noctis_19-Oct-14 0:09 
GeneralRe: Some typos / mistakes Pin
Shivprasad koirala19-Oct-14 16:56
mvpShivprasad koirala19-Oct-14 16:56 
GeneralRe: Some typos / mistakes Pin
_Noctis_19-Oct-14 17:33
professional_Noctis_19-Oct-14 17:33 
GeneralRe: Some typos / mistakes Pin
Nicholas Marty17-Nov-14 0:25
professionalNicholas Marty17-Nov-14 0:25 
GeneralRe: Some typos / mistakes Pin
_Noctis_17-Nov-14 2:10
professional_Noctis_17-Nov-14 2:10 
QuestionUseful Article! Pin
Cheung Tat Ming12-Oct-14 6:45
memberCheung Tat Ming12-Oct-14 6:45 
AnswerRe: Useful Article! Pin
Afzaal Ahmad Zeeshan18-Oct-14 22:27
professionalAfzaal Ahmad Zeeshan18-Oct-14 22:27 
GeneralMy vote of 1 Pin
Sheikh Neyamat10-Oct-14 0:34
memberSheikh Neyamat10-Oct-14 0:34 
GeneralRe: My vote of 1 Pin
Shivprasad koirala10-Oct-14 0:58
mvpShivprasad koirala10-Oct-14 0:58 
QuestionNice Article Pin
amit.malina9-Oct-14 22:41
memberamit.malina9-Oct-14 22:41 
AnswerRe: Nice Article Pin
Shivprasad koirala9-Oct-14 23:38
mvpShivprasad koirala9-Oct-14 23:38 
Generalsuper like Pin
Member 104982979-Oct-14 0:45
professionalMember 104982979-Oct-14 0:45 
GeneralMy vote of 5 Pin
Sanjay K. Gupta8-Oct-14 18:57
professionalSanjay K. Gupta8-Oct-14 18:57 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun8-Oct-14 16:34
memberHumayun Kabir Mamun8-Oct-14 16:34 
Suggestionvery nice Pin
BillW338-Oct-14 7:16
professionalBillW338-Oct-14 7:16 
GeneralRe: very nice Pin
Shivprasad koirala8-Oct-14 16:42
mvpShivprasad koirala8-Oct-14 16:42 
Questionpotential exception, naming, etc. Pin
Nicholas Marty8-Oct-14 4:49
professionalNicholas Marty8-Oct-14 4:49 
AnswerRe: potential exception, naming, etc. Pin
Shivprasad koirala8-Oct-14 16:42
mvpShivprasad koirala8-Oct-14 16:42 
GeneralRe: potential exception, naming, etc. Pin
David Rush18-Oct-14 19:34
professionalDavid Rush18-Oct-14 19:34 
GeneralMy vote of 5 Pin
Afzaal Ahmad Zeeshan8-Oct-14 2:38
professionalAfzaal Ahmad Zeeshan8-Oct-14 2:38 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170915.1 | Last Updated 19 Oct 2014
Article Copyright 2014 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid