.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> OOPS >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Way to access private members of an object from another object

Posted By:Virendra Dugar       Posted Date: October 30, 2009    Points: 10    Category: OOPS    URL: http://www.dotnetspark.com  
 

Way to access private members of an object from another object.

Create a sample class which have private variables. See below Code. 

public class Sample

{
private int i;
internal int j;
protected int k;
private static string str;
}



In other class, access Private variables via reflection. 

class Program

{
static void Main(string[] args)
{
Type t= typeof(Sample);
//To access members of any class use MemberInfo class.
MemberInfo[] mem = t.GetMembers();
BindingFlags PB = BindingFlags.NonPublic | BindingFlags.Instance;
//To access field of any class use FieldInfo class.
FieldInfo[] f = t.GetFields(PB);
foreach (FieldInfo m in f)
{
Console.WriteLine(m.Name);
}
}



We need to use BindingFlags to search for the private member. 

BindingFlags PB = BindingFlags.NonPublic | BindingFlags.Instance;


This line creates a BindingFlag which tells that search for NonPublic members. We must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return. 

If we use this Binding 

BindingFlags PB = BindingFlags.NonPublic | BindingFlags.Instance;


We will not be able to access private static string str; as it is static. BindingFlags.Instance denotes to search for non-static field. We need to use BindingFlags.Static to find out static members. 

This will give list of all the private fields (Static or non-static) 

BindingFlags PB = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;


Thanks,

Virendra Dugar


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend