C# Code - To invoke a private method


This C# .net Code snippet is all about invoking a private method.We are going to achieve this by task using Reflection. By breaking the rules OOPS.Here is the simple example done .net Console Application.

In this article i am going to explain how to invoke a PRIVATE method. usually in oops we cannot invoke or call a method when it is declared private. Then how can we invoke it.

.net provides us the feature of Reflection where we can still go ahead and invoke the private method . Reflection breaks the rules of OOPS and calls the private method. The below code snippet calls the private method





using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection; // need to add this namespace

namespace SampleApp
{
class Program
{
static void Main(string[] args)
{

Console.WriteLine("********************************");
Console.WriteLine("C# Code to call a PRIVATE method");
Console.WriteLine("********************************");
Assembly objforassembly = Assembly.GetExecutingAssembly();

Type typeMyClass = objforassembly.GetType("SampleApp.Student");
Console.WriteLine("CLASS NAME -->" +typeMyClass.Name);

//Calling a private method
MethodInfo mi = typeMyClass.GetMethod("PrintStudentName", BindingFlags.NonPublic | BindingFlags.Static);
mi.Invoke(null, null);

Console.ReadLine();
}
}

///
/// Here we are declaring a Public class - Student.
/// Inside the class we have private Method - PrintStudentName
///

public class Student
{
private static void PrintStudentName()
{
Console.WriteLine("I am a private Method -->"+"The student name is Baskar");
}
}
}



Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: