ZetCode

C# attributes

last modified November 15, 2026

This article shows how to use attributes in C#. We cover built-in attributes that the compiler understands, custom attributes, reading attributes with reflection, validation and serialization attributes, caller information attributes, and generic attributes.

An attribute is declarative metadata attached to a program element: an assembly, a type, a method, a property, a parameter, a return value, and so on. Attributes are written in square brackets before the element, for instance [Obsolete] or [JsonIgnore]. They do not change the code of the element they decorate. Instead, other code reads them: the compiler, the runtime, frameworks such as ASP.NET Core or System.Text.Json, test runners, and our own code using reflection.

An attribute is a class derived from System.Attribute. By convention, its name ends with Attribute; the suffix can be omitted when the attribute is applied, so [Obsolete] refers to the ObsoleteAttribute class. Constructor arguments are passed in parentheses, and public properties can be set with named arguments, as in [Table("invoices", Schema = "sales")]. Arguments must be compile-time constants, typeof expressions, or arrays of them.

The Obsolete attribute

The Obsolete attribute marks a member that should no longer be used. The compiler issues a warning whenever the member is called.

Program.cs
var calc = new Calculator();

Console.WriteLine(calc.Add(2, 3));
Console.WriteLine(calc.Sum(2, 3));

class Calculator
{
    [Obsolete("Use Sum instead")]
    public int Add(int x, int y) => x + y;

    public int Sum(int x, int y) => x + y;
}

The Add method is marked as obsolete.

[Obsolete("Use Sum instead")]
public int Add(int x, int y) => x + y;

The message tells the users of the method what to use instead. The program still compiles and runs; the build prints the CS0618 warning. If we pass error: true as the second argument, the warning turns into the CS0619 error and the program no longer compiles.

$ dotnet build
Program.cs(3,19): warning CS0618: 'Calculator.Add(int, int)' is obsolete: 'Use Sum instead'
$ dotnet run
5
5

The Conditional attribute

The Conditional attribute makes the compiler remove calls to a method unless a given symbol is defined.

Program.cs
using System.Diagnostics;

Log("application started");
Console.WriteLine("doing work");
Log("application finished");

[Conditional("DEBUG")]
static void Log(string message) =>
    Console.WriteLine($"[debug] {message}");

The Log method is called only in the Debug configuration, which defines the DEBUG symbol.

[Conditional("DEBUG")]
static void Log(string message) =>

The method itself stays in the compiled assembly; only the calls are omitted, including the evaluation of their arguments. A conditional method must return void. The Debug.WriteLine and Debug.Assert methods are implemented this way.

$ dotnet run
[debug] application started
doing work
[debug] application finished
$ dotnet run -c Release
doing work

The Flags attribute

The Flags attribute tells the runtime that an enumeration is a set of bit flags whose values can be combined.

Program.cs
using System.Reflection;

Permissions p1 = Permissions.Read | Permissions.Write;
Color c1 = Color.Red | Color.Blue;

Console.WriteLine(p1);
Console.WriteLine(c1);
Console.WriteLine(typeof(Permissions).IsDefined(typeof(FlagsAttribute)));

[Flags]
enum Permissions
{
    None = 0,
    Read = 1,
    Write = 2,
    Execute = 4
}

enum Color
{
    Red = 1,
    Green = 2,
    Blue = 4
}

We combine members of two enumerations with the bitwise OR operator.

[Flags]
enum Permissions

The values of a flags enumeration are powers of two, so each member occupies its own bit.

Console.WriteLine(p1);
Console.WriteLine(c1);

The ToString method of the Permissions value lists the names of the set flags. The Color enumeration has the same kind of values but lacks the attribute; its combined value is printed as the number 5.

Console.WriteLine(typeof(Permissions).IsDefined(typeof(FlagsAttribute)));

The IsDefined method checks whether the attribute is applied to a type. This is how the runtime itself detects flags enumerations.

$ dotnet run
Read, Write
5
True

Custom attributes

We create a custom attribute by deriving a class from Attribute. The attribute is read at run time with reflection.

Program.cs
using System.Reflection;

foreach (var type in new[] { typeof(Invoice), typeof(Customer) })
{
    var attr = type.GetCustomAttribute<TableAttribute>();

    Console.WriteLine(attr is null
        ? $"{type.Name}: no table"
        : $"{type.Name}: table {attr.Name}, schema {attr.Schema}");
}

[AttributeUsage(AttributeTargets.Class)]
class TableAttribute(string name) : Attribute
{
    public string Name { get; } = name;
    public string Schema { get; init; } = "dbo";
}

[Table("invoices", Schema = "sales")]
class Invoice { }

class Customer { }

The Table attribute maps a class to a database table, the way ORM libraries do.

[AttributeUsage(AttributeTargets.Class)]
class TableAttribute(string name) : Attribute

The AttributeUsage attribute, applied to an attribute class, says where the attribute may be used; here only on classes. Applying it to a method would be a compile-time error. The name parameter is a positional argument.

public string Schema { get; init; } = "dbo";

Public settable properties become named arguments. They are optional.

[Table("invoices", Schema = "sales")]
class Invoice { }

The attribute is applied with one positional and one named argument.

var attr = type.GetCustomAttribute<TableAttribute>();

The GetCustomAttribute extension method returns the attribute instance or null if the type does not have it. The attribute object is created only when we ask for it.

$ dotnet run
Invoice: table invoices, schema sales
Customer: no table

Multiple attributes

By default, an attribute can be applied to an element only once. The AllowMultiple property of AttributeUsage lifts this restriction.

Program.cs
using System.Reflection;

var methods = typeof(Tasks).GetMethods(BindingFlags.Public | BindingFlags.Static);

foreach (var method in methods)
{
    foreach (var tag in method.GetCustomAttributes<TagAttribute>())
    {
        Console.WriteLine($"{method.Name}: {tag.Value}");
    }
}

class Tasks
{
    [Tag("io")]
    [Tag("slow")]
    public static void Backup() { }

    [Tag("cpu")]
    public static void Compress() { }

    public static void Cleanup() { }
}

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
class TagAttribute(string value) : Attribute
{
    public string Value { get; } = value;
}

The Tag attribute can be applied to a method several times.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]

Without AllowMultiple = true, the second Tag on the Backup method would cause the CS0579 duplicate attribute error.

foreach (var tag in method.GetCustomAttributes<TagAttribute>())

The plural GetCustomAttributes method returns all instances of the attribute. We read them for each public static method of the Tasks class.

$ dotnet run
Backup: io
Backup: slow
Compress: cpu

Validation attributes

The System.ComponentModel.DataAnnotations namespace contains attributes that describe validation rules. ASP.NET Core and Entity Framework Core use them, and we can check them ourselves with the Validator class.

Program.cs
using System.ComponentModel.DataAnnotations;

var users = new[]
{
    new User { Name = "John Doe", Email = "john@example.com", Age = 34 },
    new User { Name = "", Email = "roger", Age = 150 },
};

foreach (var user in users)
{
    var context = new ValidationContext(user);
    var results = new List<ValidationResult>();

    if (Validator.TryValidateObject(user, context, results, validateAllProperties: true))
    {
        Console.WriteLine($"{user.Name}: valid");
        continue;
    }

    foreach (var result in results)
    {
        Console.WriteLine(result.ErrorMessage);
    }
}

class User
{
    [Required]
    [StringLength(50, MinimumLength = 2)]
    public string Name { get; init; } = "";

    [EmailAddress]
    public string Email { get; init; } = "";

    [Range(0, 120)]
    public int Age { get; init; }
}

The properties of the User class carry validation attributes.

[Required]
[StringLength(50, MinimumLength = 2)]
public string Name { get; init; } = "";

The name is required and must have between 2 and 50 characters. The Required attribute treats an empty string as a missing value.

if (Validator.TryValidateObject(user, context, results, validateAllProperties: true))

The TryValidateObject method reads the attributes with reflection and checks the property values. Without validateAllProperties: true, only the Required attributes would be checked. The failures are collected in the results list. For the second user, only the Required error is reported for the name; when a property fails Required, its other attributes are skipped.

$ dotnet run
John Doe: valid
The Name field is required.
The Email field is not a valid e-mail address.
The field Age must be between 0 and 120.

Serialization attributes

Serializers read attributes to customize their output. System.Text.Json has its own set of attributes in the System.Text.Json.Serialization namespace.

Program.cs
using System.Text.Json;
using System.Text.Json.Serialization;

var product = new Product { Id = 1, Title = "Pen", Price = 1.2m, InternalCode = "X-17" };

string json = JsonSerializer.Serialize(product);
Console.WriteLine(json);

var back = JsonSerializer.Deserialize<Product>("""{"product_id":2,"name":"Ink","price":3.5}""");
Console.WriteLine($"{back!.Id} {back.Title} {back.Price} '{back.InternalCode}'");

class Product
{
    [JsonPropertyName("product_id")]
    public int Id { get; init; }

    [JsonPropertyName("name")]
    public string Title { get; init; } = "";

    [JsonPropertyName("price")]
    public decimal Price { get; init; }

    [JsonIgnore]
    public string InternalCode { get; init; } = "";
}

We rename the properties in JSON and leave one of them out.

[JsonPropertyName("product_id")]
public int Id { get; init; }

The Id property is written and read as product_id.

[JsonIgnore]
public string InternalCode { get; init; } = "";

The JsonIgnore attribute excludes the property from both serialization and deserialization.

$ dotnet run
{"product_id":1,"name":"Pen","price":1.2}
2 Ink 3.5 ''

Caller information attributes

Caller information attributes are applied to optional parameters. The compiler fills in the arguments at the call site.

Program.cs
using System.Runtime.CompilerServices;

int[] vals = [1, 2, 3];

Diag.Check(vals.Length > 5);
Diag.Check(vals.Contains(2));

new Repository().Save();

class Repository
{
    public void Save() => Diag.Trace("saving data");
}

static class Diag
{
    public static void Check(bool condition,
        [CallerArgumentExpression(nameof(condition))] string expr = "")
    {
        Console.WriteLine($"{expr}: {condition}");
    }

    public static void Trace(string message,
        [CallerMemberName] string member = "",
        [CallerFilePath] string path = "",
        [CallerLineNumber] int line = 0)
    {
        Console.WriteLine($"{message} ({member}, {Path.GetFileName(path)}:{line})");
    }
}

The Check method receives the source text of its argument, and the Trace method the calling member, file, and line.

[CallerArgumentExpression(nameof(condition))] string expr = "")

The CallerArgumentExpression attribute gives us the expression passed to the condition parameter as a string. It is used by ArgumentNullException.ThrowIfNull and similar guard methods.

[CallerMemberName] string member = "",
[CallerFilePath] string path = "",
[CallerLineNumber] int line = 0)

The values are compile-time constants inserted by the compiler, so they cost nothing at run time. The Trace method is called from a class method on purpose. Top-level statements and the local functions declared in them belong to the generated <Main>$ method, and CallerMemberName would return that name.

$ dotnet run
vals.Length > 5: False
vals.Contains(2): True
saving data (Save, Program.cs:12)

Generic attributes

Since C# 11, attribute classes can be generic. A type argument replaces the older pattern of passing a Type object to the constructor.

Program.cs
using System.Reflection;

foreach (var prop in typeof(Order).GetProperties())
{
    var attr = prop.GetCustomAttribute<ConverterAttribute>();
    string conv = attr?.ConverterType.Name ?? "none";

    Console.WriteLine($"{prop.Name}: {conv}");
}

[AttributeUsage(AttributeTargets.Property)]
abstract class ConverterAttribute : Attribute
{
    public abstract Type ConverterType { get; }
}

class ConverterAttribute<T> : ConverterAttribute
{
    public override Type ConverterType => typeof(T);
}

class ConverterTypeAttribute(Type type) : ConverterAttribute
{
    public override Type ConverterType => type;
}

class UpperCaseConverter { }
class DateConverter { }

class Order
{
    [Converter<UpperCaseConverter>]
    public string Code { get; init; } = "";

    [ConverterType(typeof(DateConverter))]
    public DateOnly Date { get; init; }

    public int Quantity { get; init; }
}

We define two attributes that specify a converter for a property: a generic one and one that takes a Type argument.

class ConverterAttribute<T> : ConverterAttribute
{
    public override Type ConverterType => typeof(T);
}

The generic attribute is applied as [Converter<UpperCaseConverter>]. Unlike typeof arguments, type arguments can be checked with constraints.

var attr = prop.GetCustomAttribute<ConverterAttribute>();

Each closed generic attribute, such as ConverterAttribute<UpperCaseConverter>, is a distinct type, unrelated to a non-generic class of the same name. To find all of them in one call, both attributes derive from the abstract ConverterAttribute base class; GetCustomAttribute also returns attributes of derived types.

$ dotnet run
Code: UpperCaseConverter
Date: DateConverter
Quantity: none

Source

Attributes and reflection

Attributes interpreted by the C# compiler

In this article we have worked with attributes in C#. See also the JSON, enum, generics, and primary constructors tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.