Friday, August 10, 2007

Can you call private member of a class from another class?

Can you call private member of a class from another class?

Very strange question right?

but answer is yes. Shocked???

Check out the following code.

It is done by dot net framwork reflection

suppose we have a class


public class Class1
{

public Class1()
{


}

private string IAmCalled()
{


return "I am private member and I am called by somebody. shame on me.";

}

}

Add following line to other class/page from which you want to access private member

using System.Reflection;

Just write follwoing code in other class/page and you will see the magic


Class1 cls = new Class1();

Type t = typeof(Class1);

object obj = t.InvokeMember("IAmCalled", BindingFlags.InvokeMethod BindingFlags.NonPublic BindingFlags.Instance, null, cls, null);

Response.Write(obj.ToString());

It works!!!

please share if you have some more information.

No comments: