Knowledge Management Banner

Knowledge Management Banner

C# : Attributes : Part 21

Attributes

  • An attribute tag is used for declaration, which is used to provide basic information about the behaviour of method, classes, structures, etc.
  • The declaration of attribute can be done by writting the attribute in square bracket above the element for which you neeed to add
  • few Pre defined attributes in .net are as follows
    • Obsolete : It is used to make class, method, fields outdated.
    • WebMethod : To expose a method as an xml web service method.
    • Serializable : Indicates that a class can be serialized. When you are working on cross domain application, e.g. service. if the object will be crossing cross domain boundaries than those classes needs to be serialized.
  • Example
  •  [Obsolete]  
     public static int addNum(int a, int b)  
     {  
       return a + b;  
     }  
    
  • If the above method is called in the programm it will give warning with green underline for it.
  • Refer following figure


  • When a string message is also specified along with Obsolete, it will give warning from where the method is called along with the typed message
  • Refer following figure 


  • The above technique is generally used when the developers tries to use old method but is warned to use the new method instead.
  • The old method is also to be kept it cannot be removed so as to keep the backward compatibility.
  • Thus using attribute Obselete provide the best way to throw warning or message.
  • Attribute Obselete can be also used to throw error by writing true along with the message, Refer following image




No comments

Powered by Blogger.