This article shows three ways to access a Private Member of a class from another class.
Introduction
After some playing with private variables and their behavior I have found three ways to access private members from another class. Here this is very simple logic that may help you to access the private members. The three ways are as follows.
- Access the private member using reflection
- Access the private member using base by sub-class
- Access the private member by methods.
Access the private member using reflection
As we know, reflection is a way to access the members of a class. So we can use the "System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance" flags using the GetField method, as per the following code.
namespace Access_Private_Member
{
class Program
{
static void Main(string[] args)
{
ExampleOne one = new ExampleOne();
}
}
public class Tamil
{
private string message = "தமிழ் வாழ்க!";
}
public class ExampleOne : Tamil
{
public ExampleOne()
{
System.Reflection.FieldInfo receivedObject = typeof(Tamil).GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)[0];
var obj = receivedObject.GetValue(this);
MessageBox.Show("Access the private member using Reflection \n "+obj.ToString());
}
}
}
Access the private member using base by sub-class
This is another way that uses the class as a sub-class and accesses the private member using the base. The following code demonstrates the logic.
namespace Access_Private_Member
{
class Program
{
static void Main(string[] args)
{
TamilValga.ExampleTwo two = new TamilValga.ExampleTwo();
}
}
public class TamilValga
{
private string message = "தமிழ் வாழ்க!";
public class ExampleTwo : TamilValga
{
public ExampleTwo()
{
MessageBox.Show("Access the private member using base by sub-class \n " + base.message);
}
}
}
}
Access the private member by methods
This is a very simple way to access the private member of a class without inheriting the class by declaring a public method of the same class as per the following code.
namespace Access_Private_Member
{
class Program
{
static void Main(string[] args)
{
Tamil three = new Tamil();
MessageBox.Show("Acess the private member by methods \n" + three.AccessPriveMemberMessage("தமிழ் வாழ்க! தமிழ் வளர்க!!"));
}
}
public class Tamil
{
private string message = "தமிழ் வாழ்க!";
public string AccessPriveMemberMessage(string value)
{
message = value;
return message;
}
}
}