Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discovering derived types using reflection

Using reflection, is it possible to discover all types that derive from a given type?

Presumably the scope would be limited to within a single assembly.

like image 391
xyz Avatar asked Mar 02 '10 10:03

xyz


People also ask

What is reflection in .NET with example?

Reflection provides objects that encapsulate assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object. You can then invoke the type's methods or access its fields and properties.

What is reflection in net please describe a use case and the benefits of using it?

Reflection enables you to use code that was not available at compile time. . NET Reflection allows application to collect information about itself and also manipulate on itself. It can be used effectively to find all the types in an assembly and/or dynamically invoke methods in an assembly.

What is Microsoft reflection?

You can now use your Windows Device as a mirror without leaving your desk or wherever you go. The Reflection app allows you to have a quick check of yourself and zoom to the right level just for what you need. Obviously, you want to make sure you do have a webcam before you install this app.


2 Answers

pretty much the same as Darin's but here you go..

    public static List<Type> FindAllDerivedTypes<T>()     {         return FindAllDerivedTypes<T>(Assembly.GetAssembly(typeof(T)));     }      public static List<Type> FindAllDerivedTypes<T>(Assembly assembly)     {         var derivedType = typeof(T);         return assembly             .GetTypes()             .Where(t =>                 t != derivedType &&                 derivedType.IsAssignableFrom(t)                 ).ToList();      }  

used like:

var output = FindAllDerivedTypes<System.IO.Stream>();             foreach (var type in output)             {                 Console.WriteLine(type.Name);             } 

outputs:

NullStream SyncStream __ConsoleStream BufferedStream FileStream MemoryStream UnmanagedMemoryStream PinnedBufferMemoryStream UnmanagedMemoryStreamWrapper IsolatedStorageFileStream CryptoStream TailStream 
like image 85
Hath Avatar answered Sep 21 '22 20:09

Hath


var derivedTypes = from t in Assembly.GetExecutingAssembly().GetTypes()                    where t.IsSubclassOf(typeof(A))                    select t; 
like image 33
Sergej Andrejev Avatar answered Sep 21 '22 20:09

Sergej Andrejev