Gets all types that have the specified attribute - CSharp System

CSharp examples for System:Attribute

Description

Gets all types that have the specified attribute

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Reflection;
using System.Linq;
using System.Collections.Generic;
using System;/*from  ww  w .  ja  v  a 2  s .  com*/

public class Main{
        /// <summary>
      /// Gets all types that have the specified attribute
      /// </summary>
      /// <typeparam name="T">The attribute.</typeparam>
      /// <param name="assembly">The assembly.</param>
      /// <returns></returns>
      /// <gist id="41883d902a6ed6bd8da4">This sample shows AppDomain, but works the same for assemblies as well.</gist>
      public static IEnumerable<Type> WithAttribute<T>(this Assembly assembly) where T : Attribute {
         return assembly.GetLoadableTypes().WithAttribute<T>();
      }
        /// <summary>
      /// Gets the loadable types.
      /// </summary>
      /// <param name="assembly">The assembly.</param>
      /// <returns>Returns an IEnumerable of Types that can be loaded.</returns>
      /// 
      public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) {
         try {
            return assembly.GetTypes();
         } catch(ReflectionTypeLoadException e) {
            return e.Types.Where(t => t != null);
         }
      }
}

Related Tutorials