Using attributes in c#

In the .NET Framework there are many reasons to use attributes, like

  • Defining which classes are serializable
  • Choosing which methods are exposed in a Web service
  • As per definition at MSDN
    Attributes allow us to add descriptions to classes, properties, and methods at design time that can then be examined at runtime via reflection.”

    Consider this example:
    Say you have a class which has a method from older version which is still in use for any reason and now you have come up with a new version of the class which makes fantastic use of Generic List and LINQ and has a new method for similar purpose. You would like developers to prefer the new one provided in the later version of your library. How will you do that ? One way is to write in the documentation. A better way is to use attribute as follow.

    public class AccountsManager
          [Obsolete("prefer GetAccountsList", true)]
          static Account[] GetAccounts( ) { }    
          static List<Account> GetAccountsList( ) { }      

    If an obsolete method is used when the program is compiled, the developer gets this info and decides accordingly.

    AccountManager.GetAccounts() is obsolete: prefer GetAccountsList

    We may also create and add Custom Attributes as per requirements.

    References :

  • Use the advantages of custom attributes in your C# applications
  • Using Attributes in C#
  • Advertisements

    Leave a Reply

    Fill in your details below or click an icon to log in: Logo

    You are commenting using your account. Log Out /  Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out /  Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out /  Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out /  Change )


    Connecting to %s