Latest web development tutorials

C # properties (Attribute)

Characteristics (Attribute) is a program for transferring various elements (such as classes, methods, structures, enumerations, components, etc.) in the run-time behavior of declarative tag information.You can add declarative information to the program by using the feature. A statement label is applied by placing it in front of the elements in square brackets ([]) to describe.

Characteristics (Attribute) to add metadata, such as compiler instructions and comments, description, methods, additional information and so on. .Net Framework provides two types of features:predefinedproperties andcustomproperties.

Predetermined properties (Attribute)

Predetermined properties (Attribute) the following syntax:

[Attribute (positional_parameters, name_parameter = value, ...)]
element

Characteristics (Attribute) names and values ​​are specified within square brackets, placed before the element to which it applies. positional_parameters predetermined necessary information, name_parameter predetermined optional information.

Predefined attributes (Attribute)

.Net Framework provides three predefined attributes:

  • AttributeUsage
  • Conditional
  • Obsolete

AttributeUsage

Predefined attributesAttributeUsage describes how to use a custom attribute class.It specifies the type of properties can be applied to the project.

Provisions of this feature has the following syntax:

[AttributeUsage (
   validon,
   AllowMultiple = allowmultiple,
   Inherited = inherited
)]

among them:

  • Validon predetermined parameters characteristic language elements can be placed. It is a combination of enumeratorsAttributeTargetsvalue. The default value isAttributeTargets.All.
  • Parameterallowmultiple (optional)provides a Boolean value for the propertyAllowMultipleproperty (property). If true, then this feature is more useful. The default value is false (single use).
  • Parametersinherited (optional)provides a Boolean value for the propertyInheritedproperty (property). If true, this property is a derived class can be inherited. The default value is false (not inherited).

E.g:

[AttributeUsage (AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property, 
AllowMultiple = true)]

Conditional

This feature marks a predefined condition method, its implementation depends on its top preprocessing identifier.

It will cause conditional compilation of method calls, depending on the specified value such asDebug or Trace.For example, the value of the variable is displayed when debugging code.

Provisions of this feature has the following syntax:

[Conditional (
   conditionalSymbol
)]

E.g:

[Conditional ( "DEBUG")]

The following example demonstrates this feature:

#define DEBUG
using System;
using System.Diagnostics;
public class Myclass
{
    [Conditional ( "DEBUG")]
    public static void Message (string msg)
    {
        Console.WriteLine (msg);
    }
}
class Test
{
    static void function1 ()
    {
        Myclass.Message ( "In Function 1.");
        function2 ();
    }
    static void function2 ()
    {
        Myclass.Message ( "In Function 2.");
    }
    public static void Main ()
    {
        Myclass.Message ( "In Main function.");
        function1 ();
        Console.ReadKey ();
    }
}

When the above code is compiled and executed, it produces the following results:

In Main function
In Function 1
In Function 2

Obsolete

The predefined attributes tagged program entities should not be used. It allows you to tell the compiler to discard a particular target element. For example, when a new method is used in a class, but you still want to keep the class in the old method, you can display a new method should be used instead of the old method of message to mark it as obsolete (outdated of).

Provisions of this feature has the following syntax:

[Obsolete (
   message
)]
[Obsolete (
   message,
   iserror
)]

among them:

  • Parametermessage,is a string that describes the project as well as the reasons why the outdated what the alternative uses.
  • Parametersiserror,is a Boolean value. If true, the compiler should use the project as a mistake. The default value is false (the compiler generates a warning).

The following example demonstrates this feature:

using System;
public class MyClass
{
   [Obsolete ( "Do not use OldMethod, use NewMethod instead", true)]
   static void OldMethod ()
   { 
      Console.WriteLine ( "It is the old method");
   }
   static void NewMethod ()
   { 
      Console.WriteLine ( "It is the new method"); 
   }
   public static void Main ()
   {
      OldMethod ();
   }
}

When you try to compile the program, the compiler will give an error message stating:

 Do not use OldMethod, use NewMethod instead

Create custom attributes (Attribute)

.Net Framework allows you to create custom properties for storing declarative information, and can be retrieved at runtime. This information is based on design criteria and the application needs to be associated with any target element.

Create and use custom features include four steps:

  • Statement Custom Properties
  • Build Custom Properties
  • Apply custom properties on the target program element
  • Access through reflection characteristics

The final step includes write a simple program to read the metadata to find the various symbols. Metadata is data and information used to describe other data. The program should use reflection to access properties at runtime. We will discuss this in detail in the next chapter.

Statement Custom Properties

A new custom properties to be derived fromSystem.Attribute class.E.g:

// BugFix a custom attribute is assigned to the class and its members [AttributeUsage (AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

public class DeBugInfo: System.Attribute

In the above code, we have declared a custom attribute namedDeBugInfoof.

Build Custom Properties

Let us build a custom attribute namedDeBugInfo,the information will be stored in the feature debugger obtained. It stores the following information:

  • bug code number
  • Developers recognize the name of the bug
  • Date of the last review of the code
  • A string message store developers mark

OurDeBugInfofirst three classes will be used to store three private property information (property) and with a public property to store messages for (property). So bug numbers developer name and the date of the review will be required positioning DeBugInfo class (positional) parameter, the message is an optional name (named) parameters.

Each property must have at least one constructor. Required positioning (positional) parameter that should be passed by the constructor. The following code demonstratesDeBugInfocategories:

// BugFix a custom attribute is assigned to the class and its members [AttributeUsage (AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

public class DeBugInfo: System.Attribute
{
  private int bugNo;
  private string developer;
  private string lastReview;
  public string message;

  public DeBugInfo (int bg, string dev, string d)
  {
      this.bugNo = bg;
      this.developer = dev;
      this.lastReview = d;
  }

  public int BugNo
  {
      get
      {
          return bugNo;
      }
  }
  public string Developer
  {
      get
      {
          return developer;
      }
  }
  public string LastReview
  {
      get
      {
          return lastReview;
      }
  }
  public string Message
  {
      get
      {
          return message;
      }
      set
      {
          message = value;
      }
  }
}

Apply custom properties

By placing properties immediately before its target to apply this feature:

[DeBugInfo (45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
[DeBugInfo (49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
class Rectangle
{
  // Member variables protected double length;
  protected double width;
  public Rectangle (double l, double w)
  {
      length = l;
      width = w;
  }
  [DeBugInfo (55, "Zara Ali", "19/10/2012",
  Message = "Return type mismatch")]
  public double GetArea ()
  {
      return length * width;
  }
  [DeBugInfo (56, "Zara Ali", "19/10/2012")]
  public void Display ()
  {
      Console.WriteLine ( "Length: {0}", length);
      Console.WriteLine ( "Width: {0}", width);
      Console.WriteLine ( "Area: {0}", GetArea ());
  }
}

In the next chapter, we will use the Reflection class object to retrieve this information.