Commonly Used Attributes in C# and What They Do

An attribute attaches metadata to a class, method, property or parameter. On its own it does nothing: something has to read it. Sometimes that is the compiler ([Obsolete]), sometimes a framework at run time ([JsonPropertyName], [Required]), and sometimes a designer in Visual Studio ([Browsable]). Knowing who reads an attribute tells you what it can and cannot do.

Below are the attributes that come up most in everyday C#, grouped by who reads them.

Read by the compiler

using System.Diagnostics;

public class Mailer
{
    [Obsolete("Use SendAsync instead.")]
    public void Send() { }

    [Obsolete("Removed in v3. Use SendAsync instead.", true)]
    public void SendLegacy() { }

    public Task SendAsync() => Task.CompletedTask;

    [Conditional("DEBUG")]
    public static void Trace(string message) => Console.WriteLine(message);
}

[Obsolete] makes every caller get warning CS0618, or error CS0619 when the second argument (error) is true. Since .NET 5 you can also set DiagnosticId so callers can suppress your warning on its own, without hiding every other obsolete warning.

[Conditional("DEBUG")] removes calls to the method when the DEBUG symbol is not defined, as in a Release build. The method itself is still compiled; only the calls disappear, including the evaluation of their arguments. It only works on methods that return void.

[Flags] on an enum changes how combined values are formatted and parsed. It has its own post, linked at the end.

Caller information

These go on optional parameters, and the compiler fills in the values at each call site:

using System.Runtime.CompilerServices;

public static class Guard
{
    public static void Require(
        bool condition,
        [CallerArgumentExpression(nameof(condition))] string? expression = null,
        [CallerMemberName] string member = "",
        [CallerLineNumber] int line = 0)
    {
        if (!condition)
            throw new ArgumentException($"{member} (line {line}): '{expression}' failed.");
    }
}

A call like Guard.Require(order.Total > 0); reports the text order.Total > 0 along with the calling method and line number, with no string written by hand. [CallerArgumentExpression] needs C# 10; nameof on a parameter inside the attribute needs C# 11. The other caller attributes ([CallerMemberName], [CallerFilePath], [CallerLineNumber]) date back to C# 5. ArgumentNullException.ThrowIfNull uses the same technique to put the parameter name in its message.

Serialization

For JSON with System.Text.Json:

using System.Text.Json.Serialization;

public class Website
{
    [JsonPropertyName("url")]
    public string Url { get; set; } = "";

    [JsonIgnore]
    public DateTime LastChecked { get; set; }
}

For XmlSerializer, the equivalents are [XmlRoot] (name of the root element), [XmlElement] (serialize as a child element, optionally renamed), [XmlAttribute] (serialize as an attribute instead of an element) and [XmlIgnore] (skip the member).

[Serializable] marks a type for binary serialization with BinaryFormatter. That serializer is insecure and obsolete, and from .NET 9 its implementation is removed (every call throws), so you only need [Serializable] when maintaining code that still uses it. JSON and XML serializers ignore it.

Validation

System.ComponentModel.DataAnnotations attributes are read by ASP.NET Core model binding, Blazor forms, Entity Framework Core and Validator.TryValidateObject:

using System.ComponentModel.DataAnnotations;

public class SignUp
{
    [Required, EmailAddress]
    public string Email { get; set; } = "";

    [Required, StringLength(100, MinimumLength = 12)]
    public string Password { get; set; } = "";

    [Range(13, 120)]
    public int Age { get; set; }
}

Nothing checks these automatically when you set a property. Validation only happens when a framework, or your own call to Validator, runs it.

Designer and property grid metadata

These come from System.ComponentModel and matter mostly for WinForms controls, the PropertyGrid and other designer-driven tools:

AttributeEffect
[DisplayName("Web Site URL")]Name shown in the property grid instead of the member name
[Description("...")]Help text shown under the property grid
[Category("Appearance")]Group the property appears in
[DefaultValue("https://csharpexamples.com")]Value the designer treats as default (not bolded, not written to designer code)
[Browsable(false)]Hide the property from the property grid
[EditorBrowsable(EditorBrowsableState.Never)]Hide the member from IntelliSense in other projects
[TypeConverter(typeof(ExpandableObjectConverter))]Let a nested object expand in the property grid

A common mistake with [DefaultValue]: it does not set the property’s value. You still need an initializer (= "https://csharpexamples.com"); the attribute only tells tools what that default is.

Interop and assembly-level attributes

[LibraryImport] (.NET 7) and the older [DllImport] declare a function from a native library. LibraryImport generates the marshalling code at compile time and works with Native AOT.

[assembly: InternalsVisibleTo("MyApp.Tests")] lets a test project use internal members. In SDK-style projects you can put <InternalsVisibleTo Include="MyApp.Tests" /> in the project file instead.

[ComVisible(false)] controls whether types are exposed to COM. It is only relevant for Windows COM interop.

Writing your own

A custom attribute is a class that derives from Attribute, usually with [AttributeUsage] to say where it may be applied. Reading it back is a reflection call such as member.GetCustomAttribute<MyAttribute>(). The enum description post below shows the full round trip.

Related examples

Leave a Comment