Using C# Reflection, you can investigate at runtime what Attributes are applied not only to classes but also to methods.
This is useful for checking method metadata during debugging or for scenarios where you want to extract and execute only methods marked with specific attributes within a custom framework.
Implementing Retrieval of Method Attributes
The following sample code uses the GetCustomAttributes method to retrieve and display all attributes (such as DebuggerStepThrough or Conditional) applied to the Output method.
Sample Code
using System;
using System.Diagnostics; // For DebuggerStepThrough, Conditional
using System.Reflection;
public class Program
{
public static void Main()
{
// 1. Get target type information
Type type = typeof(MySample);
// 2. Get information of the method to investigate
// Using nameof handles renaming during refactoring
MethodInfo method = type.GetMethod(nameof(MySample.Output));
if (method != null)
{
Console.WriteLine($"Attributes applied to method '{method.Name}':\n");
// 3. Get all custom attributes
// Passing true as the argument includes inherited attributes in the search
object[] attributes = method.GetCustomAttributes(inherit: true);
foreach (var attr in attributes)
{
// The ToString() of the attribute class is called, displaying the type name
Console.WriteLine($"- {attr}");
}
}
}
}
// Sample Class
public class MySample
{
// Apply multiple attributes
// DebuggerStepThrough: Tells the debugger not to step into this method
// Conditional: Includes this method in compilation only if the symbol is defined
[DebuggerStepThrough]
[Conditional("DEBUG_TRACE")]
public void Output(double num)
{
Console.Write($"num = {num}");
}
}
Execution Result
Attributes applied to method 'Output':
- System.Diagnostics.DebuggerStepThroughAttribute
- System.Diagnostics.ConditionalAttribute
Explanation and Technical Points
1. GetCustomAttributes Method
Calling this method on a MethodInfo object allows you to retrieve all attribute instances applied to that method as an object[] (or Attribute[]).
- No arguments: Retrieves only attributes defined directly on that member.
- Argument (
bool inherit): Iftrue, it also searches for attributes on methods in the parent class if the method is overridden.
2. When You Want Only Specific Attributes
If you want to retrieve only a specific attribute (e.g., just ConditionalAttribute) rather than all of them, it is smarter to use the generic version of the extension method.
// Retrieve specific attributes (returns an empty array if none exist)
var conditionalAttrs = method.GetCustomAttributes<ConditionalAttribute>();
3. Leveraging Metadata
In framework development (e.g., Unit Test Runners or Web API routing), a common pattern is to “find methods marked with a specific attribute and execute logic based on the settings (URL, timeout, etc.) defined in that attribute.” The GetCustomAttributes method used here is the foundational technology for such operations.
