How to Access Private Method Outside the Class in C#

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 
  1. System
  2. System.Reflection 
Step 3: Now create a class and inside that class create one method that will be private as follows:
  1. class PrivateMethodClass  
  2.     {  
  3.         //Private Method
  4.         private void PrivateMethod()  
  5.         {  
  6.             Console.WriteLine("\n\n\n\t Hello C-Sharp Corner\n\t This is a Private Method!! :D\n\n");  
  7.         }  
  8.     }  
Step 4: Now by using the main method call the method as follows:
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             typeof(PrivateMethodClass).GetMethod("PrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(new PrivateMethodClass(), null);  
  6.         }  
  7.     }  
Complete Code: 
  1. using System;  
  2. using System.Reflection;  
  3.   
  4. namespace PrivateMethodAccess  
  5. {  
  6.     class PrivateMethodClass  
  7.     {  
  8.         //Method is declared as private...  
  9.         private void PrivateMethod()  
  10.         {  
  11.             Console.WriteLine("\n\n\n\t Hello C-Sharp Corner\n\t This is a Private Method!! :D\n\n");  
  12.         }  
  13.     }  
  14.   
  15.     class Program  
  16.     {  
  17.         static void Main(string[] args)  
  18.         {  
  19.             typeof(PrivateMethodClass).GetMethod("PrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(new PrivateMethodClass(), null);  
  20.         }  
  21.     }  
  22. }  
Output
Output 

Up Next
    Ebook Download
    View all
    Learn
    View all
    sourabhsomani.com