Open In App

Attribute Usage and Retrieval in C#

Last Updated : 24 Oct, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

An attribute is a declarative tag placed inside square brackets ([ ]) before a code element. It describes certain characteristics or rules that apply to that element. Attributes extend the information about your program beyond what is defined by the language syntax itself.

Example:

C#
[Obsolete("Use NewMethod instead")]
public void OldMethod()
{
    Console.WriteLine("This method is obsolete");
}

Here, [Obsolete] is an attribute that tells the compiler the method should no longer be used.

Example: Using a Built-in Attribute

C# provides several built-in attributes that convey intent to the compiler or runtime. The [Obsolete] attribute is one of the most common examples. It marks methods, classes or properties as outdated and optionally displays a warning or error during compilation.

C#
using System;

public class Logger
{
    [Obsolete("Use LogInfo instead")]
    public void LogMessage()
    {
        Console.WriteLine("Old logging method");
    }

    public void LogInfo()
    {
        Console.WriteLine("New logging method");
    }
}

class Program
{
    static void Main()
    {
        Logger logger = new Logger();
        logger.LogMessage(); // Compiler warning
    }
}

Explanation:

  • [Obsolete] alerts developers that a particular method or class is deprecated.
  • The message string provides guidance about the preferred alternative.
  • You can make it a compile-time error by adding a second parameter:
C#
[Obsolete("Use LogInfo instead", true)]

Creating Custom Attributes

Developers can define their own attributes to add domain-specific metadata. To create a custom attribute, derive a class from System.Attribute.

Example:

C#
using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class InfoAttribute : Attribute
{
    public string Author { get; }
    public string Version { get; }

    public InfoAttribute(string author, string version)
    {
        Author = author;
        Version = version;
    }
}

Applying the Custom Attribute

C#
[Info("Ravi", "2.1")]
public class Calculator
{
    [Info("Ravi", "2.2")]
    public void Add() => Console.WriteLine("Addition executed");
}

The [AttributeUsage] attribute defines where the attribute can be applied. In this example, it can decorate both classes and methods.

Understanding AttributeUsage

The [AttributeUsage] attribute defines how and where a custom attribute can be applied.

Common Parameters

  • AttributeTargets: Specifies valid program elements like Class, Method or Property.
  • AllowMultiple: Indicates whether multiple instances can be applied to the same element.
  • Inherited: Specifies whether the attribute is inherited by derived classes.

Example:

C#
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class ValidateAttribute : Attribute
{
    public string Rule { get; }
    public ValidateAttribute(string rule)
    {
        Rule = rule;
    }
}

Retrieving Attributes Using Reflection

Attributes can be accessed at runtime using reflection, allowing programs to read metadata and act upon it dynamically.

C#
using System;
using System.Reflection;

[Info("Amit", "1.0")]
public class Student
{
    [Info("Amit", "1.1")]
    public void Display() => Console.WriteLine("Student Info");
}

class Program
{
    static void Main()
    {
        Type type = typeof(Student);

        // Retrieve class-level attributes
        var classAttributes = type.GetCustomAttributes(typeof(InfoAttribute), false);
        foreach (InfoAttribute attr in classAttributes)
        {
            Console.WriteLine($"Class Author: {attr.Author}, Version: {attr.Version}");
        }

        // Retrieve method-level attributes
        MethodInfo method = type.GetMethod("Display");
        var methodAttributes = method.GetCustomAttributes(typeof(InfoAttribute), false);
        foreach (InfoAttribute attr in methodAttributes)
        {
            Console.WriteLine($"Method Author: {attr.Author}, Version: {attr.Version}");
        }
    }
}

Output:

Class Author: Amit, Version: 1.0

Method Author: Amit, Version: 1.1

The GetCustomAttributes method retrieves the metadata applied to a class or method. This metadata can then be used to modify logic or perform validation at runtime.

Retrieving Specific Attributes

If you need only one specific attribute, you can use the generic form of GetCustomAttribute.

Example:

C#
InfoAttribute attr = Attribute.GetCustomAttribute(typeof(Student), typeof(InfoAttribute)) as InfoAttribute;
Console.WriteLine($"{attr.Author} - {attr.Version}");

Or using generics:

C#
var attr = (InfoAttribute)Attribute.GetCustomAttribute(typeof(Student), typeof(InfoAttribute));

Best Practices

  • Derive custom attributes from System.Attribute.
  • Use [AttributeUsage] to limit where attributes apply and improve clarity.
  • Keep attribute logic lightweight. They should define metadata, not behavior.
  • Use reflection carefully since it can affect performance.
Suggested Quiz
3 Questions

What is the main purpose of attributes in C#?

  • A

    To control program flow at runtime

  • B

    To extend metadata information about program elements

  • C

    To replace comments in source code

  • D

    To improve execution speed

Explanation:

Attributes provide metadata about classes, methods, properties, etc., which can be accessed by the compiler or at runtime using reflection

Which base class must be inherited to create a custom attribute in C#?

  • A

    System.Object

  • B

    System.Reflection.Attribute

  • C

    System.Attribute

  • D

    System.Metadata

Explanation:


Which reflection method is used to retrieve custom attributes applied to a class or method?

  • A

    GetAttributes()

  • B

    GetCustomAttributes()

  • C

    GetDeclaredAttributes()

  • D

    GetMetadata()

Explanation:


Image
Quiz Completed Successfully
Your Score :   2/3
Accuracy :  0%
Login to View Explanation
1/3 1/3 < Previous Next >

Article Tags :

Explore