What is an attribute in C#, and how do you apply one to a class or method?
Short answer
An attribute is metadata attached to a code element (class, method, property, etc.) using square-bracket syntax placed directly above it — attributes don't affect runtime behavior on their own, but tools, frameworks, and your own reflection code can read them to alter behavior…
Advertisement
AModel answer
An attribute is metadata attached to a code element (class, method, property, etc.) using square-bracket syntax placed directly above it — attributes don't affect runtime behavior on their own, but tools, frameworks, and your own reflection code can read them to alter behavior or generate documentation.
[Obsolete("Use NewMethod instead")]
public void OldMethod() { }
[Serializable]
public class Product { public string Name { get; set; } = ""; }Real-world example
Marking a deprecated API method with [Obsolete] so callers get a compiler warning, or marking a class [Serializable] for legacy binary serialization.
Likely follow-ups
- Can you apply multiple attributes to the same code element?
Related topics