An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute. A declarative tag is depicted by square ([ ]) brackets placed above the element it is used for.
Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods and classes to a program. The .Net Framework provides two types of attributes: the pre-defined attributes and custom built attributes.
The .NET Framework provides several predefined attributes, but three of the most commonly used ones are:
Obsolete Attribute:
- Namespace:
System
- Purpose: Indicates that a program element (class, method, property, etc.) is obsolete and should not be used. The compiler generates a warning or error if the obsolete member is used.
- Usage:csharp
1[Obsolete("This method is obsolete. Use NewMethod instead.")] 2public void OldMethod() 3{ 4 // Implementation 5}
- Namespace:
Serializable Attribute:
- Namespace:
System
- Purpose: Marks a class as serializable, allowing its instances to be converted to a format that can be stored or transmitted (e.g., for saving to a file or sending over a network).
- Usage:csharp
1[Serializable] 2public class MySerializableClass 3{ 4 public int Id { get; set; } 5 public string Name { get; set; } 6}
- Namespace:
DllImport Attribute:
- Namespace:
System.Runtime.InteropServices
- Purpose: Specifies the name of the DLL that contains the unmanaged function to be called from managed code. This is commonly used for Platform Invocation Services (P/Invoke) to call functions from native libraries.
- Usage:csharp
1[DllImport("user32.dll")] 2public static extern int MessageBox(int hWnd, string text, string caption, int type);
- Namespace:
Creating a Custom Attribute
- Define a class that inherits from
Attribute
. - Use the
AttributeUsage
attribute to specify where your custom attribute can be applied.
csharp1[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] 2public class CustomAttribute : Attribute 3{ 4 public string Description { get; } 5 6 public CustomAttribute(string description) 7 { 8 Description = description; 9 } 10}
Applying Custom Attributes
You can apply your custom attribute to classes or methods like this:
csharp1[Custom("This is a custom attribute")] 2public class MyClass 3{ 4 [Custom("This method does something special")] 5 public void MyMethod() 6 { 7 // Method implementation 8 } 9}
Retrieving Attribute Information
You can retrieve the information from attributes using reflection. Here’s an example of how to do that:
csharp1Type type = typeof(MyClass); 2CustomAttribute attribute = (CustomAttribute)Attribute.GetCustomAttribute(type, typeof(CustomAttribute)); 3Console.WriteLine(attribute.Description);