Use .NET Reflection with C# to call Private/Protected Methods

Some days ago I needed to write some tests for an old Windows Service. I was not authorized to make any changes in the Code of the Service (and its libraries), so in order to invoke some protected/private method I needed to use the reflection. What follows, is the code I used: nothing complicated, but maybe can save a bit of your time in case you need to achieve the same 🙂

The name of the method I needed to call is “OnStart”.

MethodInfo onStart = typeof(Service).GetMethod("OnStart"BindingFlags.NonPublic | BindingFlags.Instance);

if (onStart != null)
{
       object result = null;
       ParameterInfo[] parameters = onStart.GetParameters();
       object classInstance = Activator.CreateInstance(typeof(Service), null);
 
       var parameterType = parameters[0].ParameterType;
                
       object[] parametersArray = (object[])Activator.CreateInstance(parameterType1);
       result = onStart.Invoke(classInstanceparametersArray);
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s