MemberInfo.GetCustomAttributes Method
.NET Framework 3.5
When overridden in a derived class, returns custom attributes applied to this member.
This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.
| Name | Description | |
|---|---|---|
|
GetCustomAttributes(Boolean) | When overridden in a derived class, returns an array of all custom attributes applied to this member. |
|
GetCustomAttributes(Type, Boolean) | When overridden in a derived class, returns an array of custom attributes applied to this member and identified by Type. |
Generic extensions for retrieving custom attributes
As most of the Reflection classes, such as Type, MemberInfo, and ParameterInfo, all implement ICustomAttributeProvider, you can add some extension methods (new to C# 3.0 and Visual Basic 9.0) to extend this interface to make retrieving attributes a little easier.
For example:
[C#]
using System;
using System.Reflection;
public static class CustomAttributeProviderExtensions
{
public static T[] GetCustomAttributes<T>(this ICustomAttributeProvider provider) where T : Attribute
{
return GetCustomAttributes<T>(provider, true);
}
public static T[] GetCustomAttributes<T>(this ICustomAttributeProvider provider, bool inherit) where T : Attribute
{
if (provider == null)
throw new ArgumentNullException("provider");
T[] attributes = provider.GetCustomAttributes(typeof(T), inherit) as T[];
if (attributes == null)
{ // WORKAROUND: Due to a bug in the code for retrieving attributes
// from a dynamic generated parameter, GetCustomAttributes can return
// an instance of an object[] instead of T[], and hence the cast above
// will return null.
return new T[0];
}
return attributes;
}
}
This allows you to do the following:
[C#]
[Serializable]
class Program
{
static void Main(string[] args)
{
SerializableAttribute[] attributes = typeof(Program).GetCustomAttributes<SerializableAttribute>();
foreach (var attribute in attributes)
{
Console.WriteLine(attribute);
}
}
}
Which outputs the following:
SerializableAttribute
- 11/23/2008
- David M. Kean