How to Call C# Private Methods from External Classes

Often times during testing, you may need totest the value of a privte method. The following code shows how to dothis for both methods and vars by getting the methods or vars from anexternal class and then placing them into a text file. If you have anyquestions on how to use this, email me. Happy Coding!!

 

using System;
using System.Reflection;
using System.Collections;
using System.IO;
namespace Private2Public
{
/// <summary>
/// Summary description for cCallPrivate.
/// </summary>
public class CallPrivate
{
private const string final = "Void Finalize()";
private const string getHash = "Int32 GetHashCode()";
private const string boolEquals = "Boolean Equals(System.Object)";
private const string toStr = "System.String ToString()";
private const string getType = "System.Type GetType()";
private const string memClone = "System.Object MemberwiseClone()";

/// <summary>
///
/// </summary>
public CallPrivate()
{
}
/// <summary>
/// Calls a private variable from an external class.
/// </summary>
/// <param name="instance" />Instance of the object
/// <param name="name" />Name of the private variable to call
/// <returns></returns>
public object GetPrivateField( object instance, string name )
{

Type t = instance.GetType();
FieldInfo f = t.GetField( "wasCalled", BindingFlags.Instance
| BindingFlags.NonPublic
| BindingFlags.Public );

return f.GetValue( instance );
}

/// <summary>
/// Calls a private method from an external class
/// </summary>
/// <param name="instance" />Instance of the object
/// <param name="name" />Name of the method to call
/// <param name="paramList" />Array of params that are passed to the method.
/// eg A method that has 2 params (an int = 5 and a string = "one two")
///
/// <returns>Invokes the method from the object</returns>
/// <example> This example shows how to use both the
/// GetPrivateMethod and the GetPrivateField methods.
///
/// try
/// {
/// Numbers acc= new Numbers();
/// CallPrivate cp = new CallPrivate();
///
/// bool wasCalled =
/// (bool)cp.GetPrivateFieldValue(acc,"wasCalled");
/// lock(this)
/// {
/// int strlen = (int)cp.GetPrivateMethod(acc,"Multiply",Squared);
/// this.textBox1.Text =
/// "The value from the of strlen is " +
/// strlen + "\r" + wasCalled.ToString();
/// }
/// }
/// catch (Exception ex)
/// {
/// MessageBox.Show(
/// ex.Message + ex.GetBaseException().ToString());
/// }
///

/// </example>
public object GetPrivateMethod( object instance, string name, params object[] paramList )
{
Type t = instance.GetType();
Type[] paramTypes = new Type[ paramList.Length ];

for ( int i = 0; i < paramList.Length; i++ )
{
paramTypes[i] = paramList[i].GetType();
}

MethodInfo m = t.GetMethod( name, BindingFlags.Instance
| BindingFlags.NonPublic
| BindingFlags.Public,
null,
paramTypes,
null );

return m.Invoke( instance, paramList );
}
/// <summary>
/// Returns an arraylist of the Private Methods
/// </summary>
/// <param name="t" />Type
/// <returns>An arraylist of the Private Methods</returns>
public ArrayList ListPrivateMethods(Type t)
{
ArrayList arr = new ArrayList();
for(int i = 0; i < t.GetMethods(BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance).Length ; i++)
{
switch (t.GetMethods(BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance)[i].ToString())
{
case final:
continue;
case getHash:
continue;
case boolEquals:
continue;
case toStr:
continue;
case getType:
continue;
case memClone:
continue;
default:
arr.Add(t.GetMethods(BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance)[i].ToString());
break;
}
}
return arr;
}
/// <summary>
/// Returns an arraylist of the Private Methods
/// </summary>
/// <param name="t" />Type
/// <returns>An arraylist of the Private Methods</returns>
public ArrayList ListPrivateFields(Type t)
{
ArrayList arr = new ArrayList();
for(int i = 0; i < t.GetFields(BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance).Length ; i++)
{
switch (t.GetFields(BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance)[i].ToString())
{
case "Void Finalize()":
continue;
case "Int32 GetHashCode()":
continue;
case "Boolean Equals(System.Object)":
continue;
case "System.String ToString()":
continue;
case "System.Type GetType()":
continue;
case "System.Object MemberwiseClone()":
continue;
default:
arr.Add(t.GetFields(BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance)[i].ToString());
break;
}
}
return arr;
}
/// <summary>
/// Write the methods to a File.
/// </summary>
///
/// <param name="t" />Class type
///
/// <param name="FileName" />
/// File Name of the file to write to
///
public void WriteMethodsToFile(Type t, string FileName)
{
ArrayList methods = ListPrivateMethods(t);
ArrayList fields = ListPrivateFields(t);

if(File.Exists(FileName))
{
File.Delete(FileName);
}
StreamWriter sw = new StreamWriter(FileName,true);
for(byte i = 0; i < methods.Count; i++)
{
sw.WriteLine("Methods: " );
sw.WriteLine(methods[i].ToString());

}
methods.Clear();

for(byte i = 0; i < fields.Count; i++)
{
if(i==0)
{
sw.WriteLine("");
sw.WriteLine("");
sw.WriteLine("Vars: " );
}

sw.WriteLine(fields[i].ToString());

}
sw.Close();
fields.Clear();
}
}
}

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!