Getting C# attribute constructor arguments via reflection

Development .NET Core

2 years ago

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:

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