Generic Method to Get Custom Attribute of Specified Type

This blog defines generic method to get custom attribute of specified type.
 

using System;

using System.Collections.Generic;

using System.Reflection;

/// <summary>

/// Enum Helper class

/// </summary>

public class EnumHelper

{

    /// <summary>

    /// Used to get specified Custom Attribute of specified type.

    /// </summary>     

    /// <typeparam name="B">Type</typeparam>

    /// <typeparam name="T">Custom attribute</typeparam>

    public static T GetCustomAttribute<B, T>(B value)

    {

        Type type = value.GetType();

        FieldInfo fieldInfo = type.GetField(value.ToString());

        T[] attribs = fieldInfo.GetCustomAttributes(

             typeof(T), false) as T[];

        return attribs[0];

    }

}

Ebook Download
View all
Learn
View all