Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
        }
    }
}
like image 753
SrividhyaShama Avatar asked Dec 15 '13 11:12

SrividhyaShama


3 Answers

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();
        }
    }
}
like image 151
Chandan Kumar Avatar answered Oct 05 '22 22:10

Chandan Kumar


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.

like image 26
O. R. Mapper Avatar answered Oct 05 '22 22:10

O. R. Mapper


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.

like image 36
ppetrov Avatar answered Oct 05 '22 23:10

ppetrov