Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Assembly.GetTypes() require references?

I want to get all of the types from my assembly, but I don't have the references, nor do I care about them. What does finding the interface types have to do with the references? and is there a way for me to get around this?

Assembly assembly = Assembly.LoadFrom(myAssemblyPath);
Type[] typeArray = assembly.GetTypes();

Throws: FileNotFoundException Could not load file or assembly 'Some referenced assembly' or one of its dependencies. The system cannot find the file specified.

like image 423
Peter Avatar asked Nov 10 '11 00:11

Peter


People also ask

How do you get type objects from assemblies that have not been loaded?

GetTypes to obtain Type objects from assemblies that have not been loaded, passing in the name of the type or types you want. Use Type. GetType to get the Type objects from an assembly that is already loaded.

Which of the given methods is used in C# to get the details about information types in an assembly during runtime?

Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System. Reflection namespace.


2 Answers

Loading an assembly requires all of its dependencies to be loaded as well, since code from the assembly can be executed after it's loaded (it doesn't matter that you don't actually run anything but only reflect on it).

To load an assembly for the express purpose of reflecting on it, you need to load it into the reflection-only context with e.g. ReflectionOnlyLoadFrom. This does not require loading any referenced assemblies as well, but then you can't run code and reflection becomes a bit more awkward than what you 're used to at times.

like image 111
Jon Avatar answered Oct 01 '22 17:10

Jon


It seems to be a duplicate of Get Types defined in an assembly only, where the solution is:

public static Type[] GetTypesLoaded(Assembly assembly)
{
    Type[] types;
    try
    {
        types = assembly.GetTypes();
    }
    catch (ReflectionTypeLoadException e)
    {
        types = e.Types.Where(t => t != null).ToArray();
    }

    return types;    
}
like image 27
Shane Lu Avatar answered Sep 30 '22 17:09

Shane Lu