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

24.8k views Asked by At

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
        }
    }
}
4

There are 4 answers

2
Chandan Kumar On BEST ANSWER

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();
        }
    }
}
0
user3104183 On

You could via Reflection, but why would you want to do that?

1
O. R. Mapper On

Other than by using reflection, you cannot. As a matter of fact, members are made private exactly so they cannot be accessed from outside of the class.

0
ppetrov On

From what I see in your code, I think what you want is to have an accessible Add function.

If it is what you want, you don't need the class, just put your Add function in your Program class and make it static.

If you really need your class, then you should ask yourself the question: is the function I write designed to be accessible outside of the class, or should it only be called inside my class.

If the answer to the 1st question is yes, then make it public.

This is a design problem, so you should focus on this.

Even if you can access it using reflection, there are very very few cases when it is a good thing to do. Reflection is the last resort, if you can do it in another way, you should use the other way.