Tuesday, June 12, 2012

What is a C# Attribute?

What is a C# Attribute? 

Real short answer: It is a way of tacking declarative information into C# code (as opposed to something that actually generates code that does something like assigning a variable). You can use reflection to look up attributes. You can use system defined declarations or your own. Syntax uses square brackets such as [System.Attribute]

Common attributes:

  1. [System.Serializable]
    [Obsolete("Don't use Old method, use New method", true)]
    see main article: What is a C# Attribute? 
    
    
    
    

    Attributes (C#)

    msdn.microsoft.com/en-us/library/z0w1kczw(v=vs.80).aspx


    Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth). Once associated with a program entity, the attribute can be queried at run time using a technique calledReflection.

    Attributes exist in two forms: attributes that are defined in the Common Language Runtime's base class library and custom attributes that you can create, to add extra information to your code. This information can later be retrieved programmatically.

    In this example, the attribute System.Reflection.TypeAttributes.Serializable is used to apply a specific characteristic to a class:
    [System.Serializable]
    public class SampleClass
    {
        // Objects of this type can be serialized.
    }
    
    

    Attribute Overview

    Attributes have the following properties:
    • Attributes add metadata to your program. Metadata is information embedded in your program such as compiler instructions or descriptions of data.
    • Your program can examine its own metadata using Reflection. See Accessing Attributes With Reflection.
    • Attributes are commonly used when interacting with COM.

    Related Sections

  2. Attributes Tutorial (C#)

    msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx
    Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth). Once associated with a ...
  3. Introduction to Attributes (C#)

    msdn.microsoft.com/en-us/library/aa288059(v=vs.71).aspx
    C# provides a mechanism for defining declarative tags, called attributes, which you ...This section provides a general introduction to attributes in C#; for more ...
  4. Attributes in C# - CodeProject

    [This has a pretty good intro to how to create your own user-built attributes]]
    www.codeproject.com › Languages › C# › Beginners

     Rating: 4.8 - 137 reviews
    Sep 24, 2002 – In this tutorial we will see how we can create and attach attributes to various program entities, and how we can retrieve attribute information in a ...


    1. Developing Custom Attributes

      Now we will see how we can develop our own attributes. Here is a small recipe to create our own attributes.
      Derive our attribute class from System.Attribute class as stated in C# language specification (A class that derives from the abstract class System.Attribute, whether directly or indirectly, is an attribute class. The declaration of an attribute class defines a new kind of attribute that can be placed on a declaration) and we are done.
      using System;
      public class HelpAttribute : Attribute
      {
      }
      
      Believe me or not we have just created a custom attribute. We can decorate our class with it as we did with obsolete attribute.
      [Help()]
      public class AnyClass
      {
      }
      
      Note: it is a convention to use the word Attribute as a suffix in attribute class names. However, when we attach the attribute to a program entity, we are free not to include the Attribute suffix. The compiler first searches the attribute in System.Attribute derived classes. If no class is found, the compiler will add the word Attribute to the specified attribute name and search for it.
      But this attribute does nothing useful so far. To make it little useful let add something more in it.
      using System;
      public class HelpAttribute : Attribute
      {
          public HelpAttribute(String Descrition_in)
          {
              this.description = Description_in;
          }
          protected String description;
          public String Description 
          {
              get 
              {
                  return this.description;
                       
              }            
          }    
      }
      [Help("this is a do-nothing class")]
      public class AnyClass
      {
      }
      
      In above example we have added a property to our attribute class which we will query at runtime in last section.

      Defining or Controlling Usage of Our Attribute

      AttributeUsage class is another pre-defined class that will help us in controlling the usage of our custom attributes. That is, we can define attributes of our own attribute class.
      It describes how a custom attribute class can be used.
      AttributeUsage has three properties which we can set while placing it on our custom attribute. The first property is:

      ValidOn

      Through this property, we can define the program entities on which our custom attribute can be placed. The set of all possible program entities on which an attribute can be placed is listed in the AttributeTargetsenumerator. We can combine several AttributeTargets values using a bitwise OR operation.

      AllowMultiple

      This property marks whether our custom attribute can be placed more than once on the same program entity.

      Inherited

      We can control the inheritance rules of our attribute using this property. This property marks whether our attribute will be inherited by the class derived from the class on which we have placed it.
      Let's do something practical. We will place AttributeUsage attribute on own Help attribute and control the usage of our attribute with the help of it.
      using System;
      [AttributeUsage(AttributeTargets.Class), AllowMultiple = false, 
       Inherited = false ]
      public class HelpAttribute : Attribute
      {
          public HelpAttribute(String Description_in)
          {
              this.description = Description_in;
          }
          protected String description;
          public String Description
          {
              get 
              {
                  return this.description;
              }            
          }    
      }
      
      First look at AttributeTargets.Class. It states that Help attribute can be placed on a class only. This implies that following code will result in an error:
      AnyClass.cs: Attribute 'Help' is not valid on this declaration type. 
      It is valid on 'class' declarations only.
      Now try to put in on method
      [Help("this is a do-nothing class")]
      public class AnyClass
      {
          [Help("this is a do-nothing method")]    //error
          public void AnyMethod()
          {
          }
      } 
    <continued at link above>
  5. oreilly.com/catalog/progcsharp/chapter/ch18.html
    Perhaps the attribute you are most likely to use in your everyday C# programming (if you are not interacting with COM) is [Serializable] . As you'll see in Chapter ...
  6. C# Attribute Examples

    www.dotnetperls.com/attribute
    This C# tutorial shows how to use attributes. It uses Obsolete and AttributeUsage.
  7. .net - Most Useful Attributes in C# - Stack Overflow

    stackoverflow.com/questions/.../most-useful-attributes-in-c-sharp
    30 answers
    I know that attributes are extremely useful. There are some predefined ones ... [DebuggerDisplay] can be really helpful to quickly see customized output of a Type ...
  8. Lesson 16: Using Attributes - C# Station

    www.csharp-station.com/Tutorial/CSharp/lesson16
    This lesson explains how to use C# attributes. Our objectives are as follows: Understand what attributes are and why they're used; Apply various attributes with ...
  9. Elegant Code » Marker Interfaces and C# Attributes

    elegantcode.com/2008/07/30/marker-interfaces-and-c-attributes/
    Jul 30, 2008 – The marker interface is an interface that is empty. It does not implement any properties nor methods. It is used to mark the capability of a class ...

No comments:

Post a Comment