Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 203
conectionist Avatar asked Apr 19 '26 20:04

conectionist


2 Answers

With reflection, yes ( Can I change a private readonly field in C# using reflection? ), but there's probably a very good reason why the variable is set to private readonly.

like image 199
Adam Flanagan Avatar answered Apr 22 '26 10:04

Adam Flanagan


You can only use reflection

typeof(MyClass)
   .GetField("name",BindingFlags.Instance|BindingFlags.NonPublic)
   .SetValue(myclassInstance, 123);
like image 21
Mohamed Abed Avatar answered Apr 22 '26 09:04

Mohamed Abed