Calling a function inside another assembly in .NET

Red Gate .NET ReflectorI wanted to call a hash function from a .net executable from my code. My first step was to inspect the executable with Reflector.

The Hash function was in a namespace called Core:

namespace TheExe.Core
{
    internal static class AssemblyInfo
    internal static class StringExtensionMethods
}

internal static class StringExtensionMethods
{
    // Methods
    public static string Hash(this string original, string password);
    // More methods...
}

Notice that the Core namespace is marked as internal so it was not meant to be callable outside of the executable. It’s still possible to call it using Reflection:

Assembly ass = Assembly.LoadFile("TheExe");
Type asmType = ass.GetType("TheExe.Core.StringExtensionMethods");
MethodInfo mi = asmType.GetMethod("Hash", BindingFlags.Public | BindingFlags.Static);
string result = (string)mi.Invoke(null, {"blabla", "password"});

This works nicely! However if the function you want to call is overloaded (eg if there would also be a Hash function accepting 3 parameters) then you need to specify which overload you want:

Assembly ass = Assembly.LoadFile("TheExe");
Type asmType = ass.GetType("TheExe.Core.StringExtensionMethods");
MethodInfo mi = asmType.GetMethod("Hash", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(System.String), typeof(System.String) }, null);
string result = (string)mi.Invoke(null, {"blabla", "password"});

Now that was easy, wasn’t it?