Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

C# Attributes in 5 minutes

4.85/5 (128 votes)
19 Oct 2014CPOL4 min read 350.6K  
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)