What are attributes in C#?
Answer
Attributes are metadata annotations added to code elements (classes, methods, properties, parameters) using [AttributeName] syntax. They are inspected at runtime via reflection. Built-in attributes: [Obsolete("Use NewMethod instead")], [Serializable], [DllImport("user32.dll")], [HttpGet] / [Route] (ASP.NET Core routing), [Required] / [MaxLength(100)] (data annotations validation), [JsonPropertyName("first_name")] (JSON serialization). Custom attributes: inherit from System.Attribute: [AttributeUsage(AttributeTargets.Method)] public class LogAttribute : Attribute { public string Level { get; } public LogAttribute(string level) => Level = level; }. Read attributes: typeof(MyClass).GetCustomAttributes<MyAttribute>(). Attributes power many framework features: ASP.NET Core routing/model binding, EF Core schema configuration, test frameworks (NUnit's [Test], xUnit's [Fact]).
Previous
What is reflection in C#?
Next
What is the difference between IQueryable and IEnumerable in LINQ?
More C# / .NET Questions
View all →- Intermediate What is ASP.NET Core and how does it differ from ASP.NET Framework?
- Intermediate What is middleware in ASP.NET Core?
- Intermediate What is dependency injection in ASP.NET Core?
- Intermediate What is Entity Framework Core?
- Intermediate What is the difference between eager, lazy, and explicit loading in EF Core?