Getting C# attribute constructor arguments via reflection

Today I learnt that attribute constructor argument values can be retrieved via reflection without ever storing them in any field or property. The reason I realized this is that attributes in the UWP/WinUI/Uno Platform Windows.Foundation.Metadata don’t have any public members except for the constructors. So how does the code then get the passed-in values? Enter CustomAttributesData.

This handy class (see docs here) provides a static GetCustomAttributes method, which returns a list of CustomAttributesData instances for a given assembly, type, type member, or module. Instead of providing you with the custom attribute instance, this class describes the attribute and the constructor which was used. Specifically, the ConstructorArguments property returns a list of actual arguments passed-in:


using System.Reflection;
var attributeData = CustomAttributeData.GetCustomAttributes(typeof(TestClass))[0];
Console.WriteLine(attributeData.AttributeType == typeof(TestAttribute)); // true
Console.WriteLine(attributeData.ConstructorArguments[0].Value); // "Hello World"
[Test("Hello, world!")]
public class TestClass
{
}
public class TestAttribute : Attribute
{
public TestAttribute(string greeting) { }
}

For an even more convenient way to retrieve CustomAttributeData for a type, you can use GetCustomAttributesData method on Type:


var attributeData = typeof(TestClass).GetCustomAttributesData();

Buy me a coffeeBuy me a coffee

1 thought on “Getting C# attribute constructor arguments via reflection”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.