C# Attribute Features Every Developer Should Know

C# provides powerful metadata capabilities through attributes. These markers allow developers to add descriptive information to code eelments that can be inspected and utilized at runtime. Below are some practical attribute patterns that can enhance your development workflow.

Conditional Attribute for Method Filtering

The Conditional attribute enables selective method execution based on defined symbols. Methods marked with this attribute will be completely omitted during compilation unless the specified preprocessor symbol is defined.

public class ClassA
{
    public int number = 0;
    [Conditional("eeee")]
    public void TestMethodA()
    {
        Console.WriteLine("TestMethodA");
    }
}

}


</div>**Execution Result:**

No output is displayed because the `eeee` symbol is not defined. To activate the method, add the preprocessor directive at the very top of your source file:

<div>```
#define eeee

class Program
{
    static void Main(string[] args)
    {
        ClassA instance = new ClassA();
        instance.TestMethodA();
    }
    
    public class ClassA
    {
        [Conditional("eeee")]
        public void TestMethodA()
        {
            Console.WriteLine("TestMethodA");
        }
    }
}

Obsolete Attribute for Deprecation Warnings

The Obsolete attribute marks code elements as deprecated. When other developers attempt to use a marked member, the compiler displays a warning message, providing a clear signal that the code should be avoided.

Creating Custom Attributes

Custom attributes extend the metadata system by allowing you to define domain-specific markers. The following example demonstrates a reusable attribute for storing descirptive information about classes and properties.

class Program { static void Main(string[] args) { Student student = new Student() { Age = 1, Name = "Xiao Ming" };

    Type type = typeof(Student);
    foreach (PropertyInfo property in type.GetProperties())
    {
        foreach (Attribute attribute in property.GetCustomAttributes(true))
        {
            AttributeTest customAttr = (AttributeTest)attribute;
            if (customAttr != null)
            {
                Console.WriteLine(customAttr.Tips);
            }
        }
    }
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property)]
public class AttributeTest : Attribute
{
    public AttributeTest(string tips)
    {
        Tips = tips;
    }
    public string Tips { get; set; }
}

[AttributeTest("Student Class")]
public class Student
{
    [AttributeTest("Age Property")]
    public int Age { get; set; }

    [AttributeTest("Name Property")]
    public string Name { get; set; }
}

}


</div>**Output:**

<div>```
Age Property
Name Property

Tags: C# attributes conditional Obsolete reflection

Posted on Tue, 02 Jun 2026 18:46:43 +0000 by gigamike187