Access a private member of a class?
How can I access a private member of a class form another class?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Selva GanapathyPosted Apr 23, 2014, 12:07 AM
There is three ways available to achieve your requirement. Please have the following link
http://www.c-sharpcorner.com/UploadFile/6f0898/how-to-access-a-private-member-of-a-class-from-other-class/#ReadAndPostComment
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;
}
}
}
Abhay ShankerPosted Apr 22, 2014, 7:49 AM
http://msdn.microsoft.com/en-us/library/st6sy9xe.aspx
Munesh SharmaPosted Apr 22, 2014, 7:10 AM