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