Attributes in .NET
Introduction to Attributes
Attributes in .NET provide a way to add metadata, declarative information, and behavior to program elements like classes, methods, properties, and parameters.
Using Built-in Attributes
.NET provides several built-in attributes like [Obsolete]
, [Serializable]
, and [Conditional]
which can be applied to indicate deprecation, serialization support, and conditional compilation respectively.
Example: Using Built-in Attributes
using System;
[Obsolete("This method is deprecated. Use NewMethod instead.")]
public class MyClass {
[Conditional("DEBUG")]
public void DebugMethod() {
Console.WriteLine("Debugging...");
}
[Serializable]
public class SerializableClass {
public string Name { get; set; }
}
}
Creating Custom Attributes
You can create your own custom attributes by defining classes that inherit from System.Attribute
. Custom attributes can be used to annotate code with domain-specific metadata.
Example: Creating Custom Attributes
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute : Attribute {
public string Description { get; set; }
public MyCustomAttribute(string description) {
Description = description;
}
}
[MyCustom("This class represents a data entity.")]
public class DataEntity {
[MyCustom("This method performs data validation.")]
public void ValidateData() {
// Validation logic
}
}
Accessing Attributes at Runtime
Reflection in .NET allows you to inspect and retrieve attributes applied to types and members at runtime, enabling dynamic behavior based on metadata.
Example: Accessing Attributes at Runtime
using System;
using System.Reflection;
public class Program {
public static void Main() {
Type type = typeof(DataEntity);
var classAttributes = type.GetCustomAttributes(typeof(MyCustomAttribute), false);
foreach (MyCustomAttribute attribute in classAttributes) {
Console.WriteLine($"Class Attribute Description: {attribute.Description}");
}
MethodInfo method = type.GetMethod("ValidateData");
var methodAttributes = method.GetCustomAttributes(typeof(MyCustomAttribute), false);
foreach (MyCustomAttribute attribute in methodAttributes) {
Console.WriteLine($"Method Attribute Description: {attribute.Description}");
}
}
}
Conclusion
Attributes in .NET offer a powerful mechanism to annotate code with metadata and behavior, allowing for declarative programming and dynamic behavior based on runtime inspection.