1 out of 2 rated this helpful - Rate this topic

MemberInfo.GetCustomAttributes Method

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
Public method Supported by the .NET Compact Framework Supported by the XNA Framework GetCustomAttributes(Boolean) When overridden in a derived class, returns an array of all custom attributes applied to this member.
Public method Supported by the .NET Compact Framework Supported by the XNA Framework GetCustomAttributes(Type, Boolean) When overridden in a derived class, returns an array of custom attributes applied to this member and identified by Type.
Top
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
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