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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Selva GanapathyRank #560 · 4.3K reputationPosted Apr 22, 2014, 8:07 PM EDT
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;
}
}
}
Munesh SharmaRank #174 · 13.9K reputationPosted Apr 22, 2014, 3:10 AM EDT
Abhay ShankerRank #375 · 6.7K reputationPosted Apr 22, 2014, 3:49 AM EDT
http://msdn.microsoft.com/en-us/library/st6sy9xe.aspx