Attributes In C#

What are attributes in C#

Attributes are used to associate some important instruction or information regarding methods, properties or types. You can say it is a kind of comment where another user can understand what the code is used for. By using attributes any user can get the wider idea that how the code is used and how the code is related to others.

Attributes allow you to add metadata, such as compiler instruction or description of data or code of your program. Reflection is the main method of attributes from which you can retrieve the information stored in attributes.

Attributes comes in the following two types:

  1. One that are defined in the Common Language Runtime (CLR) Base class library.

  2. Another one are the custom attributes, that you can make at your own for adding extra information to your code.

The basic syntax for attributes:

• [attribute(positional_parameters, name_parameter = value, ...)]Element

One more property of attribute is their that is much more important when we use both old and new method, but we can instruct compiler that which method you have to take. At that time Obsolete method comes up, that inform the compiler to compile which method.

Obsolete ():

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace ConsoleApplication1 {  
  7.   
  8.     public class Student {  
  9.         [Obsolete("Don't use NewMethod, Please Use OldMethod"true)]  
  10.         static void OldMethod() {  
  11.             Console.WriteLine("It is the old method");  
  12.         }  
  13.         static void NewMethod() {  
  14.             Console.WriteLine("It is the new method");  
  15.         }  
  16.         public static void Main() {  
  17.             OldMethod();  
  18.         }  
  19.     }  
  20.   
  21. }  
OUTPUT



Custom Attribute
  1. [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct)]  
  2. public class Student: System.Attribute {  
  3.   
  4.     private string studentname;  
  5.     public int age;  
  6.   
  7.     public Student(string studentname) {  
  8.         this.studentname = studentname;  
  9.         age = 29;  
  10.   
  11.     }  
  12.   
  13. }  
Now you can use Student Attribute like the following code snippet:
  1. [Student(“Nilesh”, age = 30)]  
  2. Student stdnt {  
  3.     // Your Code;  
  4.   
  5. }  
Hope you liked this. Have a good day. Thank you for reading.

 


Similar Articles