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

(Last Updated On: April 8, 2017)

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

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.