Search code examples
c#readonlyprivate-members

Modify private readonly member variable?


I have the following code :

public class MyClass
{
    private readonly string name;
    public string Name
    {
        get
        {
            return name;
        }
    }
    public MyClass(string name)
    {
        this.name = name;
    }
}
class Program
{
    static void Main(string[] args)
    {
        MyClass mc = new MyClass("SomeName");
    }
}

Is there any way I can change the value of mc.name without modifying the class?


Solution

  • You can only use reflection

    typeof(MyClass)
       .GetField("name",BindingFlags.Instance|BindingFlags.NonPublic)
       .SetValue(myclassInstance, 123);