Skip to content

CSharp Attributes

Attributes in C# are metadata you can attach to assemblies, classes, methods, properties, fields, parameters, or other program elements. They provide additional information about the code, which can be accessed at runtime via reflection or used by the compiler.

  • Think of attributes as annotations that describe or modify the behavior of code elements.

  • They do not change the code directly, but can influence runtime behavior, code generation, or tooling.

Example of built-in attributes:

[Obsolete("This method is outdated, use NewMethod() instead.")]
public void OldMethod()
{
// ...
}

Here, the [Obsolete] attribute marks the method as outdated and produces a compile-time warning when used.


  1. Attributes are classes derived from the abstract base class System.Attribute.
  2. They can have positional parameters (via constructor) and named parameters (via properties).
  3. Attributes are stored in the assembly’s metadata and can be retrieved using reflection at runtime.

Example of retrieving attributes:

var method = typeof(MyClass).GetMethod("OldMethod");
var obsoleteAttr = method.GetCustomAttribute<ObsoleteAttribute>();
Console.WriteLine(obsoleteAttr.Message);

Attributes are used for:

  • Marking deprecated methods[Obsolete]
  • Controlling serialization[Serializable], [JsonProperty]
  • Enforcing code analysis rules[NotNull], [Required]
  • Unit testing[Test] in NUnit/xUnit
  • Controlling behavior in frameworks[Route("api/home")] in ASP.NET

To define a custom attribute:

  1. Derive a class from System.Attribute.
  2. Optionally define a constructor to accept positional arguments.
  3. Optionally define properties for named arguments.
  4. Use [AttributeUsage] to control where the attribute can be applied.

Syntax:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute : Attribute
{
public string Description { get; }
public int Version { get; set; } // named parameter
public MyCustomAttribute(string description)
{
Description = description;
}
}

[MyCustomAttribute("This is a demo class", Version = 1)]
public class DemoClass
{
[MyCustomAttribute("This method does something important")]
public void DemoMethod()
{
Console.WriteLine("DemoMethod executed");
}
}

6. Reading Custom Attributes via Reflection

Section titled “6. Reading Custom Attributes via Reflection”
var type = typeof(DemoClass);
// Get class attribute
var classAttr = type.GetCustomAttribute<MyCustomAttribute>();
Console.WriteLine($"Class Description: {classAttr.Description}, Version: {classAttr.Version}");
// Get method attribute
var method = type.GetMethod("DemoMethod");
var methodAttr = method.GetCustomAttribute<MyCustomAttribute>();
Console.WriteLine($"Method Description: {methodAttr.Description}");

Output:

Class Description: This is a demo class, Version: 1
Method Description: This method does something important