How to get C#.Net Assembly by name?

If this is an assembly you have referenced, I like to write a class like the following:

namespace MyLibrary {
   public static class MyLibraryAssembly {
      public static readonly Assembly Value = typeof(MyLibraryAssembly).Assembly;
   }
}

and then whenever you need a reference to that assembly:

var assembly = MyLibraryAssembly.Value;

Have you tried looking at Assembly.Load(...)?


It depends on what you're trying to accomplish.

If you just want to get the assembly, then you should call System.Reflection.Assembly.Load() (as already pointed out). That's because .NET automatically checks if the assembly has already been loaded into the current AppDomain and doesn't load it again if it has been.

If you're just trying to check whether the assembly has been loaded or not (for some diagnostics reason, perhaps) then you do have to loop over all the loaded assemblies.

Another reason you might want to loop is if you know only some of the assembly information (eg. you're not sure of the version). That is, you know enough to "recognise it when you see it", but not enough to load it. That is a fairly obscure and unlikely scenario, though.


I resolved with LINQ

Assembly GetAssemblyByName(string name)
{
    return AppDomain.CurrentDomain.GetAssemblies().
           SingleOrDefault(assembly => assembly.GetName().Name == name);
}

Tags:

C#

Assemblies