Here is a small reusable solution. This is an abstract class that will extract all attributes of type K from type T.
abstract class AbstractAttributes<T, K> { protected List<K> Attributes = new List<K>(); public AbstractAttributes() { foreach (var member in typeof(T).GetMembers()) { foreach (K attribute in member.GetCustomAttributes(typeof(K), true)) Attributes.Add(attribute); } } }
If we want to extract only attributes of type DescriptionAttribute , we will use the following class.
class DescriptionAttributes<T> : AbstractAttributes<T, DescriptionAttribute> { public List<string> Descriptions { get; set; } public DescriptionAttributes() { Descriptions = Attributes.Select(x => x.Description).ToList(); } }
This class will retrieve only attributes of type DescriptionAttribute from type T But in order to actually use this class in your context, you just need to do the following.
new DescriptionAttributes<ContractorType>().Descriptions.ForEach(x => Console.WriteLine(x));
This line of code will display all the descriptions that you used as parameters in your attributes of type DescriptionAttribute . If you need to extract some other attributes, just create a new class that comes from the AbstractAttributes<T, K> class and closes its type K with the corresponding attribute.
source share