ATTRIBUTE

An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators assemblies and etc. Attributes are used for adding metadata, such

An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators assemblies and etc.

Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods, and classes to a program.

Lets look at the simple example and understand its uses:

using System;

namespace Attributes
{
    class class1
    {
        [Obsolete]
        public void method1()
        {
            //dosomething
            Console.WriteLine("this is a method");
        }

        public void newMethod1()
        {
            Console.WriteLine("this is a new method");
        }
    }
    class Program
    { 
        static void Main(string[] args)
        {
            class1 c = new class1();
            c.method1();
            Console.ReadKey();
        }
    }
}

Now let’s look at method1 which has an obsolete attribute. When someone tries to create objectof “Class1” he will get an alert in the tooltip as below.

So there is nothing but a small piece of code which gives additional information about various components of a program. The usage of attributes doesn’t end there we can provide additional user-defined information also we can restrict the user from using them as well

[Obsolete("please enter your defined message here")]
public void Method1()
{

}

[Obsolete("YOu will get an error when trying to use this method", true)]
public void Method1()
{

}

Custom Attributes:

For creating our own attributes we would need to inherit from attribute class.

class InformationAttribute: Attribute
{
    public string Infotext { get; set; }
}
class class1
{
    [Information(Infotext ="this is a method which we are not going to use anymore")]
    public void method1()
    {
        Console.WriteLine("this is a method");
    }

    [Information(Infotext ="This is a new method which we will use from now on")]
    public void newMethod1()
    {
        Console.WriteLine("this is a new method");
    }
}

Now let us suppose you would want to restrict an information attribute to class only. For that, we could use Attribute Usage.

AttributeUsage:

It describes how a custom attribute can be used and specifies the types of items to which the custom attribute can be applied.

By simply adding the below attribute to the attribute class we can restrict adding this attribute to methods.

[AttributeUsage(AttributeTargets.Class)]
class InformationAttribute: Attribute
{
    public string Infotext { get; set; }
}

The below list is all the AttributeTargets types we can use

[AttributeUsage(
AttributeTargets.All |
AttributeTargets.Class |
AttributeTargets.Assembly |
AttributeTargets.Delegate |
AttributeTargets.Enum |
AttributeTargets.Event |
AttributeTargets.Field |
AttributeTargets.GenericParameter |
AttributeTargets.Interface |
AttributeTargets.Module |
AttributeTargets.Struct |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

If we don’t specify the AttributeTargets by default it will take “ALL” as its value.

With the help of reflection, we can read the information programmatically and then we can act upon it.

Now lets create a new attribute Validate which will validate a string

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

Now let’s create a class customer with a single property

class Customer
{
    [Validate(MaxLength = 10)]
    public string name { get; set; }
}

Next, let’s create an object and initialize the customer class in our main program

Customer c = new Customer();
c.name = "My name is Teja";

Next let’s add the below logic which will read the attribute and will validate the property with it, in case of issues it will throw an error

//the below code will get the type information
// using that information we will browse through properties using the reflection class
Type objtype = c.GetType();

//uisng reflection class to loop through properties
foreach (PropertyInfo p in objtype.GetProperties())
{
    //loop through Properties
    foreach (Attribute item in p.GetCustomAttributes(false))
    {
        ValidateAttribute val = (ValidateAttribute)item;
        if (p.Name == "name")
        {
            if(c.name.Length > val.MaxLength)
            {
                throw new Exception("length of string is greated than 10");
            }
        }
    }
}

Reflection:

Reflection objects are used for obtaining type information at runtime. It contains classes that allow you to obtain information (metadata) about the application and lets you dynamically add types, values, and objects to the application.

Applications of Reflection:

  1. It allows late binding to methods and properties.
  2. We can examine an assembly and find out the various data types, classes or method it has.
  3. It lets us create new types at runtime and lets us perform some task at runtime.
  4. It lets us read and act on attribute information at run time.

5 thoughts on “ATTRIBUTE

Leave a Reply

Your email address will not be published. Required fields are marked *