How to access private function of a class in another class in c#?

SrividhyaShama picture SrividhyaShama · Dec 15, 2013 · Viewed 18.5k times · Source

I am new to c# programming and i know public data member of class is accessible from another class.Is there any way i can access private function from another class?

This is what i have tried.please help me out.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication7
{
    class Program
    {
        private class Myclass
        {
            private int Add(int num1, int num2)
            {
                return num1 + num2;
            }
        }
        static void Main(string[] args)
        {
            Myclass aObj = new Myclass();
            //is there any way i can access private function
        }
    }
}

Answer

Chandan Kumar picture Chandan Kumar · Dec 15, 2013

Hi you can use reflection to get any component of a class.

here is one demo. Try it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ExposePrivateVariablesUsingReflection
{
    class Program
    {
        private class MyPrivateClass
        {
            private string MyPrivateFunc(string message)
            {
                return message + "Yes";
            }
        }

        static void Main(string[] args)
        {
            var mpc = new MyPrivateClass();
            Type type = mpc.GetType();

            var output = (string)type.InvokeMember("MyPrivateFunc",
                                    BindingFlags.Instance | BindingFlags.InvokeMethod |
                                    BindingFlags.NonPublic, null, mpc,
                                    new object[] {"Is Exposed private Member ? "});

            Console.WriteLine("Output : " + output);
            Console.ReadLine();
        }
    }
}