9️⃣ C# Advanced Concepts
Estimated reading: 3 minutes 30 views

πŸš€ C# Attributes – Add Metadata and Control Runtime Behavior


🧲 Introduction – Why Use Attributes in C#?

C# attributes are a powerful feature that allows you to attach metadata to your code elementsβ€”such as classes, methods, properties, and more. This metadata can be accessed at runtime via reflection, enabling frameworks, tools, and libraries to perform tasks like validation, serialization, documentation, and behavior customization.

🎯 In this guide, you’ll learn:

  • What attributes are and how they work
  • How to apply built-in and custom attributes
  • How to access attributes using reflection
  • Real-world use cases and best practices

πŸ” Core Concept – What Are Attributes?

An attribute is a class that derives from System.Attribute. It is used to annotate code elements with descriptive or declarative information that influences runtime behavior or tool functionality.


🧱 Basic Syntax

[Serializable]
public class Customer
{
    public string Name { get; set; }
}

πŸ“˜ Square brackets [] are used to apply attributes.


🧰 Built-in Attributes in C#

AttributePurpose
[Obsolete]Marks code as deprecated
[Serializable]Marks a class as serializable
[DllImport]Calls unmanaged code from DLLs
[NonSerialized]Excludes a field from serialization
[Conditional]Compiles method only if a condition is met

πŸ”£ Example – [Obsolete] Attribute

[Obsolete("Use NewMethod() instead.")]
void OldMethod()
{
    Console.WriteLine("Old method");
}

πŸ“˜ Compiler shows a warning when OldMethod() is used.


🧩 Accessing Attributes Using Reflection

var attributes = typeof(Customer).GetCustomAttributes(false);

foreach (var attr in attributes)
{
    Console.WriteLine(attr.GetType().Name);
}

πŸ“˜ Use Case: Tools and frameworks use reflection to read attribute metadata dynamically.


🧠 Creating Custom Attributes

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class InfoAttribute : Attribute
{
    public string Description { get; }
    public InfoAttribute(string description)
    {
        Description = description;
    }
}
[Info("This class processes orders.")]
public class OrderProcessor
{
    // ...
}

πŸ“˜ Use Case: Build custom validation, tagging, or documentation features.


πŸŽ›οΈ AttributeUsage Options

OptionDescription
AttributeTargetsSpecifies where the attribute can be applied
AllowMultipleAllows multiple instances on one element
InheritedAllows derived classes to inherit the attribute

πŸ’‘ Best Practices & Tips

πŸ’‘ Tip: Use attributes for declarative configuration, not for logic execution.

⚠️ Pitfall: Avoid overusing reflectionβ€”it can be performance-intensive.

πŸ“˜ Best Practice: Define custom attributes when you need metadata to influence external frameworks, logging, validation, or custom pipelines.


πŸ› οΈ Real-World Use Cases

  • βœ… Marking classes for serialization ([Serializable])
  • πŸ“Š Annotating models for ORMs like Entity Framework ([Key], [Required])
  • πŸ“‹ API documentation with [Description], [DisplayName]
  • πŸ§ͺ Unit test frameworks ([TestMethod], [TestClass])
  • πŸ“¦ Custom configuration systems, logging, or validation pipelines

πŸ“Œ Summary – Recap & Next Steps

🧡 Key Takeaways:

  • Attributes add metadata to code for runtime reflection or compile-time checks.
  • Use built-in or custom attributes to define behavioral contracts.
  • Access attribute info using reflection for dynamic logic.

βš™οΈ Real-world relevance: Attributes power frameworks like ASP.NET, NUnit, Entity Framework, Unity, and many .NET libraries.


❓ FAQ Section

❓ Can I apply multiple attributes to one element?
βœ… Yes. Separate them with commas:

[Serializable, Obsolete]

❓ Can attributes affect runtime behavior directly?
βœ… No. They provide metadata only. You must use reflection or a supporting framework to act on them.


❓ Can I inherit from other attributes when creating custom ones?
βœ… All custom attributes must inherit from System.Attribute.


❓ What is [AttributeUsage] used for?
βœ… It specifies where and how an attribute can be applied.


❓ Are attributes compiled into the final assembly?
βœ… Yes. They are included in the compiled metadata and can be accessed via reflection.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸš€ C# Attributes

Or Copy Link

CONTENTS
Scroll to Top