Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a private method from another class

Tags:

c#

I have two repository classes (RepositoryFactory and BaseRepository) implementing different interfaces within the same project. The BaseRepository class has a private method that would be now needed also in the other class, with the same implementation.

Instead of duplicate the method in order to keep it private, I was thinking to a possible alternative, although so far I could not find a good solution since by definition a private method has scope only in its own class.

Using inheritance and change the method to "protected" would also not be an option, since the two classes are not linked semantically. I cannot use a public property giving back the result of the method since the return type is void.

like image 315
Francesco Avatar asked Aug 10 '12 10:08

Francesco


1 Answers

You can use reflection. Here's an example:

MethodInfo privMethod = objInstance.GetType().GetMethod("PrivateMethodName", BindingFlags.NonPublic | BindingFlags.Instance);
privMethod.Invoke(objInstance, new object[] { methodParameters });
like image 84
Jaime Botero Avatar answered Nov 08 '22 19:11

Jaime Botero