*
🏷️ Attributes in C#
Attributes in C# are declarative tags used to add metadata to code elements like classes, methods, properties, and assemblies. They influence runtime behavior, tooling, and compilation without changing the actual logic.
📘 Syntax Example
[Obsolete("Use NewMethod instead")]
public void OldMethod() {
Console.WriteLine("This method is obsolete.");
}
📚 Types of Attributes
- Predefined Attributes: Built into .NET (e.g.,
Obsolete, Serializable, DllImport).
- Custom Attributes: User-defined by inheriting from
System.Attribute.
- Assembly-Level Attributes: Apply to the entire assembly (e.g.,
[assembly: CLSCompliant(true)]).
🧪 Custom Attribute Example
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class DeveloperInfoAttribute : Attribute {
public string DeveloperName { get; }
public string Version { get; }
public DeveloperInfoAttribute(string name, string version) {
DeveloperName = name;
Version = version;
}
}
[DeveloperInfo("Shivshanker", "1.0")]
public class MyClass {
public void Display() => Console.WriteLine("Hello from MyClass");
}
🔍 Reading Attributes via Reflection
var type = typeof(MyClass);
var attr = type.GetCustomAttribute<DeveloperInfoAttribute>();
Console.WriteLine($"Developer: {attr.DeveloperName}, Version: {attr.Version}");
✅ Best Practices
- Use attributes to annotate behavior, not to implement logic.
- Use
AttributeUsage to control where your custom attribute can be applied.
- Keep attribute constructors simple and use named parameters for optional data.
- Use reflection responsibly—cache results if performance matters.
📌 When to Use
- To mark obsolete code or provide versioning info.
- To control serialization, validation, or interop behavior.
- In frameworks and libraries to enable extensibility.
- For runtime metadata inspection (e.g., unit testing, logging).
🚫 When Not to Use
- To replace business logic—attributes are metadata, not behavior.
- In performance-critical paths—reflection can be slow.
- For dynamic behavior without proper validation or fallback.
⚠️ Precautions
- Avoid overusing attributes—they can clutter code and reduce readability.
- Use reflection carefully—handle missing attributes gracefully.
- Ensure attribute data is immutable and thread-safe.
🎯 Advantages
- Declarative: Cleanly separates metadata from logic.
- Extensible: Enables custom tooling and frameworks.
- Flexible: Works across assemblies, types, and members.
- Powerful: Enables runtime inspection and dynamic behavior.
📝 Conclusion
Attributes in C# are a powerful way to enrich your code with metadata. Whether you're marking obsolete methods, customizing serialization, or building extensible frameworks, attributes help you write cleaner, smarter, and more maintainable code.
*