Attributes in C#

In this article we will learn about Attributes in C#.
  • 3626

Introduction

An attribute is a powerful .Net language feature . Attributes provides a powerful method to adding metadata such as compiler instruction to the program itself. Metadata is the information about the data, information about type , assembly. An attributes is used to represent data in your program. An element is attached to the attributes that is known as Target of the attribute.

I have created a simple attribute as shown below:

Creating a Custom Attribute :

A sample class would look like below: 

[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]

public sealed class LooKmeAttribute : System.Attribute

{

    public string Value { get; set; } 

    public LooKmeAttribute()

    {

    } 

    public LooKmeAttribute(string value)

    {

        Value = value;

    }

}


Description Of above class

 

AttributeUsage

Describes how a custom attribute class can be used.

AttributeTargets.All

It means that the attribute we created could be applied to anything or everything. For Example: Assembly, Class, Constructor etc.

AllowMultiple = false  

If set to true, multiple instances are allowed; if set to false (the default), only one instance is allowed.

sealed class

This class can not be extensible.

LooKme Attribute

This is a attribute name.

Lets see how can I use this attribute . 

[LooKme("Including 4.0 features")]

class MyClass

{

}

 

Reflection is used to get the Class Name Type.

Example

using System;

using System.Reflection;

using System.Collections;

class CustomAttributeTest

{

    public static void Main()

    {

        Type clazz = typeof(MyClass);

        Object[] atts = clazz.GetCustomAttributes(typeof(LooKmeAttribute), false);

        foreach (LooKmeAttribute att in atts)

        {

            System.Console.WriteLine("You should fix '" + clazz.FullName + "' : " + att.Value);

        }

        Console.ReadKey();

    }

}

The output of following program

 Clipboard191.jpg

© 2020 DotNetHeaven. All rights reserved.