Friday, March 6, 2015

Having fun with C# dynamic and reflection: create a class that let us to avoid access modifier

Yeah, the title says it all.

Have you ever get tired of manually call reflection methods to get a value of an hidden field? Yes I do!

In my spare time I found a funny solution to work around this problem.
I found a dummy way to avoid access modifier without losing 'deafult' syntax: thanks to c# dynamic object!
public class MyClass
{
    private int value = 1 ; 
}
private static void Main(string[] args)
{
    MyClass myInstance = new MyClass();

    //cannot access private field 'value' here
    //myInstance.value = 2;

    dynamic myInstance2 = myInstance.Expose();

    //can do it!
    myInstance2.value = 2;
}