Access private fields of a class using reflection

Posted by Ndebata under C# category on | Points: 40 | Views : 3864
Lets say ClassA is a class having one private member called "_Age" and objA the object of classA
Get private field value

object _value= objA.GetType().GetField("_Age", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objA)

Change the private field value
objA.GetType().GetField("_Age", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objA, 20)

Comments or Responses

Posted by: Akiii on: 6/1/2011 Level:Bronze | Status: [Member] | Points: 10
hi Ndebata,

Can you please explain this code, i didnt really understand...!

Thanks and Regards
Posted by: Ndebata on: 10/5/2011 Level:Starter | Status: [Member] | Points: 10
Hi Akii,

Sorry for the late reply
I have a class called ClassA having a private field named as _Age.
class ClassA

private int _Age=15;

Using reflection I can get the value of _Age and modify the same for the object of ClassA, Above code mimics how to achieve this.

Posted by: Akiii on: 10/5/2011 Level:Bronze | Status: [Member] | Points: 10

Thanks for the explanation...


Login to post response