How can you access private method in C# from main () function?

Answer: To access private method in C# programming of a class, we need to use reflection technique. In brief, reflection objects are used to get type information at run time.  We use reflection to dynamically create an instance of a type and bind the type to an existing object that of class Car in below C# code example, or get the type from an existing object and invoke its methods or access its fields and properties.

In below program example, We are getting typeof class object Car, using the type object t, accessing the function fun() and invoking it with MethodInfo object.

Note that we need use namespace “using System.Reflection

using System;
using System.Reflection;

class Car{
     private void func(){
        Console.WriteLine("Eninge private function\n");
    }    
}

class Program
{
    static void Main(string[] args)
    {
        //create object of the class    
        Car c = new Car();

        //Get the type of object
        Type t = typeof(Car);
        
        //GetMethod : searches for the specified method i.e. "func" 
        //with specified binding constraints.    
       
        MethodInfo m = t.GetMethod("func", BindingFlags.NonPublic | BindingFlags.Instance);
      
        m.Invoke(c,null);// resolves a call to func function at run time.
       
    }
}

NOTE:In an interview, don’t worry if you don’t remember the syntax. An interviewer may just want to listen the keyword reflection as an answer. However,if we can tell steps at least, it would get him a confidence. So, just focus on typeof, getMethod and Invoke functions etc.

Using reflection in C# language, we can access the private fields, data and functions etc. You might be aware of real time use of reflection in C# UI applications. We use controls e.g. button and list etc and set the private properties from properties box itself directly.

Related Posts