Reza
Reza

Reputation: 115

How to invoke a method on a private static type (or class) in another assembly in .net?

Let's say we have an application called "app.exe" which is using an external assembly called "lib.dll", the assembly contains a static type like following

internal class Foo {
    public static Foo GetInstance(string param1, string param2) {...}
    public static Foo GetInstance(string param2)
    public string Prop { get; set; }
    public string PublicMethod(string param1) { ... }
    protected string ProtectedMethod(string param1) { ... }
}

What is the best way to call Foo.GetInstance(string, string) method and after use this instance? The class is not implementing any interface (nor does it inherit from any public class). An example is really appreciated.

Update: I know about the principle of OOP, but I'm looking for a technically possible solution here. Being it Reflection, Deturing, Hooking etc. but the most preferable is Reflection. This is merely to unblock the dev team before the 3rd party can adopt their code to fix this mistake (unfortunately we are dealing with lots of bureaucracy here).

Update: I made a mistake in the original question, there are multiple GetInstance methods with different signatures.

Upvotes: 0

Views: 3595

Answers (3)

Alessandro D'Andria
Alessandro D'Andria

Reputation: 8868

Use Type.GetType:

var type = Type.GetType("NameSpace.Foo, Assembly");

There the tricky part is the assembly-qualified name, then:

var method = type.GetMethod(
    "GetInstance", 
    BindingFlags.Public | BindingFlags.Static, 
    null, 
    new[] { typeof(string), typeof(string) }, 
    null);
method.Invoke(null, new[] { "param1", "param2" });

Upvotes: 4

Stijn Van Antwerpen
Stijn Van Antwerpen

Reputation: 1988

Assuming this class in other lib

namespace PrivateLib
{
    class MyClass
    {
        private static string Foo()
        {
            return "Hello World";
        }
    }
}

you can do

  class Program
    {
        static void Main(string[] args)
        {
            var assembly = Assembly.LoadFile(Path.GetFullPath("PrivateLib.dll"));
            var myClass = assembly.GetType("PrivateLib.MyClass");
            //var instance = myClass.GetConstructor(new Type[]{}).Invoke(new object[] { });
            var method = myClass.GetMethod("Foo", BindingFlags.NonPublic | BindingFlags.Static);
            var result = method.Invoke(null, new object[]{});
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }

Upvotes: 2

Bozhidar Stoyneff
Bozhidar Stoyneff

Reputation: 3634

You can't. This is the meaning of the internal access modifier (Friend in VB). A method marked with internal is accessible only within the assembly that defines it.

Here is the documentation about the internal access modifier.

Upvotes: 2

Related Questions