Thursday, September 26, 2013

C#: Get all derived Types from the base Type that should be able to be created via Activator.CreateInstance


        /// <summary>
        /// Get all <see cref="Type"/> from <see cref="AppDomain.CurrentDomain"/> that should be able to be created via <see cref="Activator.CreateInstance(System.Type,System.Reflection.BindingFlags,System.Reflection.Binder,object[],System.Globalization.CultureInfo) "/>.
        /// </summary>
        /// <param name="baseType"></param>
        /// <returns></returns>
        public static IEnumerable< Type > GetTypesDerivedFrom( [CanBeNull] this Type baseType ) {
            if ( baseType == null ) {
                throw new ArgumentNullException( "baseType" );
            }
            return AppDomain.CurrentDomain.GetAssemblies()
                            .SelectMany( assembly => assembly.GetTypes(), ( assembly, type ) => type )
                            .Where( arg => baseType.IsAssignableFrom( arg ) && arg.IsClass && !arg.IsAbstract );
        }

No comments: