Attributes in C#


Introducing Attributes

An attribute is a declarative tag provide information to the runtime about the behavior of programming elements such as classes, enumerators and assemblies. Attributes are declared by square brackets ([ ]) and place the preceding definition of an element such as classes and methods.

How to Apply Attributes

Attributes are applied to various elements of the code. These elements include assemblies, modules, classes, structs, enumerators, constructor, methods, properties, fields, event, interface, parameters and delegates. The information about an attribute is stored with the metadata of the elements.

Syntax of attribute declaration

[attribute(positional_parameters,name_parameters=value)]


The .NET Framework supports two categories of attributes for use in C# programs.

Predefine Attributes

Predefined attributes are supplied as part of the Common Language Runtime (CLR) and they are integrated into .NET.

Some commonly used predefined attributes provided with the .NET Framework are the following.

    Conditional

    It causes conditional compilation of method calls, depending on the specified values such as debug and trace. For example, it displays the values of variables, when debugging code. This attribute only determines the action that will occur when a methods is called. If conditional compilation of the methods are required than if and else if are used in the code.

    For example:

    [Conditional (“Debug”)]

    The other value of this attributes can be:

    [Conditional (“trace”)]

    WebMethod

    It is the exposed methods in web services. A web service is a web application that allows you to expose business functions to the other application.

    For example:
    1. [WebMethods]  
    2. Public int add(int a,int b)  
    3. {  
    4.    Return (a+b);  
    5. }  
    DLLImport

    It is an unmanaged code in the programs developed outside the .Net environment. By using the DLLImport attribute the unmanaged code residing in the DLL file can be called form the managed C# environment.

    Obsolete

    It is enabled you to inform the compiler to discard a target element such as methods of a class.
Custom Attributes

Custom attributes are attributes that you create depending on your requirements.

To create the custom attributes you need to use the following procedure:
  • Define a custom attribute
  • Name the custom attribute
  • Construct the custom attribute
  • Apply the custom attribute to the target element.


Similar Articles