0
0
C Sharp (C#)programming~5 mins

Custom attribute classes in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Custom attribute classes let you add extra information to your code parts. This helps you mark or describe things in a way your program can read later.

When you want to tag methods with special notes for later use.
When you need to mark classes with extra info for tools or frameworks.
When you want to add metadata to properties to control behavior.
When you want to create your own rules or markers that other code can check.
When you want to keep extra data about code elements without changing their logic.
Syntax
C Sharp (C#)
public class MyAttribute : System.Attribute
{
    // Add properties or fields here
    public string Info { get; set; }

    public MyAttribute(string info)
    {
        Info = info;
    }
}

Custom attribute classes must inherit from System.Attribute.

You can add properties or fields to store extra data inside the attribute.

Examples
This shows how to apply your custom attribute to a class with a string value.
C Sharp (C#)
[MyAttribute("This is a test")]
public class TestClass
{
}
Example of a custom attribute that stores an author's name and applies it to a class.
C Sharp (C#)
public class AuthorAttribute : Attribute
{
    public string Name { get; }
    public AuthorAttribute(string name) => Name = name;
}

[Author("Alice")]
public class Book
{
}
Sample Program

This program defines a custom attribute InfoAttribute with a description. It applies it to a class and a method. Then it reads and prints the descriptions at runtime.

C Sharp (C#)
using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class InfoAttribute : Attribute
{
    public string Description { get; }
    public InfoAttribute(string description) => Description = description;
}

[Info("This class does math operations")]
public class Calculator
{
    [Info("Adds two numbers")]
    public int Add(int a, int b) => a + b;
}

class Program
{
    static void Main()
    {
        var type = typeof(Calculator);
        var classAttr = (InfoAttribute)Attribute.GetCustomAttribute(type, typeof(InfoAttribute));
        Console.WriteLine($"Class info: {classAttr.Description}");

        var method = type.GetMethod("Add");
        var methodAttr = (InfoAttribute)Attribute.GetCustomAttribute(method, typeof(InfoAttribute));
        Console.WriteLine($"Method info: {methodAttr.Description}");
    }
}
OutputSuccess
Important Notes

Use [AttributeUsage] to control where your attribute can be applied (classes, methods, properties, etc.).

Attributes are a way to add metadata, not to change how code works directly.

You can read attribute data at runtime using reflection.

Summary

Custom attribute classes add extra info to code elements.

They must inherit from System.Attribute.

You apply them with square brackets [] and can read them using reflection.