Skip to content

Attributes

Attributes provide a powerful way to add metadata to your code. They enable declarative programming and can be used to modify the behavior of classes, methods, and other code elements at runtime.

Built-in Attributes

C# provides several built-in attributes that serve common purposes such as marking obsolete code, controlling serialization, and managing external dependencies.

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

[Serializable]
public class User { }

[DllImport("user32.dll")]
public static extern bool MessageBox();

Custom Attributes

Custom attributes allow you to create your own metadata that can be applied to code elements. They're useful for adding business rules, validation, or framework-specific behavior.

csharp
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorAttribute : Attribute
{
    public string Name { get; }
    public AuthorAttribute(string name) => Name = name;
}

[Author("John Doe")]
public class MyClass { }