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
}
}
}
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();
}
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With