Accessing private fields using Reflection  
Author Message
Niranjan Kumar





PostPosted: Common Language Runtime, Accessing private fields using Reflection Top

Hi,

Is is possible to access private fields using reflection . I have a requirement where I need to access a private member using reflection.

Thanks

Niranjan



.NET Development12  
 
 
Lepaca





PostPosted: Common Language Runtime, Accessing private fields using Reflection Top

Yes, but you must have enough permissions...

 
 
nobugz





PostPosted: Common Language Runtime, Accessing private fields using Reflection Top

This worked:

using System;
using System.Reflection;

public class Sample {
private int mField = 0;
public int Field {
get { return mField; }
}
}

public static class Test {
public static void Run() {
Sample obj = new Sample();
FieldInfo fld = typeof(Sample).GetField("mField", BindingFlags.Instance | BindingFlags.NonPublic);
fld.SetValue(obj, 1);
Console.WriteLine("Field value = {0}", obj.Field);
}
}



 
 
Niranjan Kumar





PostPosted: Common Language Runtime, Accessing private fields using Reflection Top

Thanks for the reply. This worked.