C# Interview Question #90

What are attributes in C#?

Advanced C# Language Features Mid-Level Intermediate

Quick Interview Answer

Attributes attach declarative metadata to assemblies, classes, methods, properties, parameters, and other program elements.

Detailed Explanation

Attributes attach declarative metadata to assemblies, classes, methods, properties, parameters, and other program elements.

Frameworks can inspect this metadata at compile time or runtime. ASP.NET Core and related libraries use attributes for routing, authorization, validation, serialization, and other behaviors.

Developers can also create custom attributes by deriving from System.Attribute.

Code Example

[Obsolete("Use NewMethod instead.")]
public void OldMethod()
{
}

public class ProductDto
{
    [Required]
    public string Name { get; set; } = string.Empty;
}