Use attributes

Completed

Attributes represent or store metadata about the behaviors of classes and methods. An attribute can be attached by simply typing the name of the attribute that is enclosed in square brackets before the declaration of class/function where it needs to be applied.

Example

For example, the SysObsoleteAttribute(message,setError) attribute can be used on methods or classes that should no longer be used. During the build process, the user will be notified with a detailed message that appears in the output windows. The first parameter is the message, and the second parameter indicates if an error (true) or a warning (false) is to be set. You can have the compiler reject or display a warning.

If the API is no longer functioning, set isError = true in the SysObsoleteAttribute attribute so the compiler will report any use of that API as a compiler error

 [SysObsoleteAttribute("The Automobile class might have faster performance.", false)]
 internal class Bicycle
 {
    // Members of the Bicycle class go here.
 }

Attribute classes

Attributes can also be created by using attribute classes. To create an attribute class, extend the SysAttribute class by adding extend SysAttribute at the end of your class declaration. You can then decorate a class with the attribute that was created from the attribute class. You can specify the attribute parameters from the constructor. In the following code, the PracticeAttribute attribute class is created, and then the RegularClass class uses PracticeAttribute as an attribute.

Example

The following example shows the declaration and design of an ordinary attribute class that you could create.

 public class PracticeAttribute extends SysAttribute
 {
   // Fields in the classDeclaration.
   StartEnd startEndEnum;
   str reason;
 }
   // Constructor.
   public void new(StartEnd _startEndEnum, str _reason)
  {
    startEndEnum = _startEndEnum;
    reason = _reason;
  }
[PracticeAttribute(StartEnd::End, "Use the RegularClass class at the end.")]
 public class RegularClass
 {
    [PracticeAttribute(Startend::Start, "Use the rehearse method at the start.")]
	public int rehearse()
    {
      // Logic goes here.
        int rehearse;
        return rehearse;
    }
      // More fields and methods belong here.
 }

Attributes have many uses, including the following:

  • Using the WebMethod attribute in Web services to indicate if the method should be callable over the Simple Object Access Protocol (SOAP) to exchange information.
  • Using DLLImportAttribute to call unmanaged code.
  • Describing the title, version, description, or trademark of an assembly.
  • Describing how to map between classes, members, and eXtensible Markup Language (XML) nodes for serialization.
  • Describing the security requirements for methods.
  • Specifying characteristics to enforce security.
  • Getting information about the caller to a method.