ProfK
ProfK

Reputation: 51064

How can I get types from a referenced assembly?

I would like to access type information from a referenced (it is a project reference) assembly. The hard way would be to resolve the assembly's file path using VS solution, and load the assembly from file, but I'm sure that since the referenced assembly is already resolved/loaded in the executing assembly, there must be a much easier way, but that way really escapes me. How can I do this?

Example, in my MainAssembly, I reference LibAssembly. Now, in code in MainAssembly, I need to iterate members of types that are defined in LibAssembly.

Upvotes: 1

Views: 587

Answers (2)

Matt B
Matt B

Reputation: 8643

The easiest way I know is to use reflection. If you have a class called MyClass defined within LibAssembly, from your main assembly you could call code like the following:

Type[] types = Assembly.GetAssembly(typeof(MyClass)).GetTypes();

This would get you all of the types within LibAssembly.

Edit:

If you didn't know any of the types beforehand and could assume that the library would be in the same physical location as the executable, maybe something along the following lines would work:

using System;
using System.IO;
using System.Reflection;

string libraryFileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "myLib.dll");
Assembly assembly = Assembly.LoadFrom(libraryFileName);
Type[] myTypes = assembly.GetTypes();

Upvotes: 3

schoetbi
schoetbi

Reputation: 12856

To get a list of all loaded assemblies you can try to ask the appdomain:

AppDomain MyDomain = AppDomain.CurrentDomain;
Assembly[] AssembliesLoaded = MyDomain.GetAssemblies();
foreach (Assembly MyAssembly in AssembliesLoaded)
{
   //
}

Then you can go through all loaded assemblies and get their types by reflection.

Upvotes: 3

Related Questions