Introduction
This article exlains how to access a private method outside of the class. It is possible using reflection.
Use the following procedure:
Step 1: Create a console application in Visual Studio.
Step 2: Add 2 namespaces
- System
- System.Reflection
Step 3: Now create a class and inside that class create one method that will be private as follows:
class PrivateMethodClass
{
//Private Method
private void PrivateMethod()
{
Console.WriteLine("\n\n\n\t Hello C-Sharp Corner\n\t This is a Private Method!! :D\n\n");
}
}Step 4: Now by using the main method call the method as follows:
class Program
{
static void Main(string[] args)
{
typeof(PrivateMethodClass).GetMethod("PrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(new PrivateMethodClass(), null);
}
}Complete Code:
using System;
using System.Reflection;
namespace PrivateMethodAccess
{
class PrivateMethodClass
{
//Method is declared as private...
private void PrivateMethod()
{
Console.WriteLine("\n\n\n\t Hello C-Sharp Corner\n\t This is a Private Method!! :D\n\n");
}
}
class Program
{
static void Main(string[] args)
{
typeof(PrivateMethodClass).GetMethod("PrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(new PrivateMethodClass(), null);
}
}
}Output


Miodrag RadisavljevićPosted Apr 12, 2019, 2:20 AM EDT
Is there any other way beside using Reflection namespace ?
gaurav jadhavPosted Oct 30, 2018, 2:06 AM EDT
Sourabh Somani plz post an example same as above that how multiple parameters than how to invoke through reflection
Shubham KumarPosted May 16, 2017, 11:30 PM EDT
If private method takes multiple parameters than how to invoke through reflection
Sujananth VisvaratnamPosted Feb 25, 2016, 2:07 AM EST
hi Sourabh Somani, can you explain me what's happening in the code
M ImranPosted May 9, 2014, 9:57 PM EDT
That's great
Shaili DashoraPosted May 2, 2014, 8:44 AM EDT
nice sourabh...
Anupam SinghPosted May 2, 2014, 4:16 AM EDT
;) reflection. nice.