Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Article

C# Attributes in 5 minutes

Rate me:
Please Sign up or sign in to vote.
4.85/5 (128 votes)
19 Oct 2014CPOL4 min read 342K   157   36
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”.

Image 1

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”.

”html”
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”.

Image 2

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.

”html”
[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.

”html”
[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.

Image 3

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.

”html”
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.

”html”
[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.

”html”
[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.

Image 4

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.

Image 5

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.

Image 6

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

”html”
[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.

”html”
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.

”html”
// 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.

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

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

”html”
// 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.

”html”
// 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.

”html”
[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.

”html”
[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.

Image 7

For Further reading do watch  the below interview preparation videos and step by step video series.

License

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


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
BugWill throw null Pin
ankitCsharpAsp9-Jul-20 8:52
ankitCsharpAsp9-Jul-20 8:52 
GeneralMy vote of 5 Pin
ankitCsharpAsp9-Jul-20 6:29
ankitCsharpAsp9-Jul-20 6:29 
QuestionShort and to the point. Pin
Member 110533103-May-18 22:14
Member 110533103-May-18 22:14 
QuestionThank you!! Pin
Robot10112-Feb-18 0:36
Robot10112-Feb-18 0:36 
GeneralGreat Article Pin
wwwx27-Apr-17 2:39
wwwx27-Apr-17 2:39 
Great Article
QuestionGetType() and Types inside Types Pin
Member 123074274-Feb-16 4:16
Member 123074274-Feb-16 4:16 
Question5 star Pin
israelfh20-Sep-15 3:42
israelfh20-Sep-15 3:42 
General5 Star Pin
manoharmind6-Jul-15 19:27
manoharmind6-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
Shashank Bisen7-Aug-15 22:40 
GeneralMy vote of 5 Pin
User 1106097914-Jan-15 8:18
User 1106097914-Jan-15 8:18 
Generalnice Pin
DataBytzAI16-Nov-14 6:35
professionalDataBytzAI16-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
professionalkoolprasad200319-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
Shivprasad 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
Cheung 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
Sheikh Neyamat10-Oct-14 0:34 
GeneralRe: My vote of 1 Pin
Shivprasad koirala10-Oct-14 0:58
Shivprasad koirala10-Oct-14 0:58 

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.