⚙️ C# / .NET Intermediate

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]).