Can I change a private readonly field in C# using reflection?
You can:
typeof(Foo)
.GetField("bar",BindingFlags.Instance|BindingFlags.NonPublic)
.SetValue(foo,567);
Can I change a private readonly inherited field in C# using reflection?
Yes, it is possible to use reflection to set the value of a readonly field after the constructor has run
var fi = this.GetType()
.BaseType
.GetField("_someField", BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(this, 1);
EDIT
Updated to look in the direct parent type. This solution will likely have issues if the types are generic.
Modify private readonly member variable?
You can only use reflection
typeof(MyClass)
.GetField("name",BindingFlags.Instance|BindingFlags.NonPublic)
.SetValue(myclassInstance, 123);
Changing read only properties with reflection
As other stated, if you need to do that, you're facing a design issue to begin with. Now, if you want to know if it's possible just for the sake of knowing, or if there's no other way on earth to do it, it's indeed possible, with the help of a very small helper library and an extension method.
Consider the following code:
class Person {
int age;
string name;
public int Age { get { return age; } }
public string Name { get { return name; } }
}
// ...
using Mono.Reflection;
using System.Reflection;
// ...
Person person = new Person (27, "jb");
PropertyInfo nameProperty = typeof (Person).GetProperty ("Name");
FieldInfo nameField = nameProperty.GetBackingField ();
nameField.SetValue (person, "jbe");
Using this code, you can get the backing field of a property with just the property, and assign a new value to the backing field. You can read more details about the implementation.
Also note that it works only for simple properties, such as:
public int Age { get { return age; } }
public string Name {
get { return name; }
set { name = value; }
}
public double Velocity { get; private set; }
If you have complex properties with custom code (which includes expression-bodied member like int Answer=> 42;
), the backing field resolver will fail as there is no backing field in such case.
Set readonly property value through reflection
You can retrieve the field info for the Test
class and use it to set the value on the derived class instance like so:
var field = typeof(Test).GetField("testValue", BindingFlags.NonPublic | BindingFlags.Instance);
field.SetValue(test, 3);
Why I can rewrite static readonly field after field initiaization by reflection?
Reflection is already breaking all the rules, including accessibility and mutability; it is effectively as powerful as unsafe
: and just like unsafe
: if something goes wrong, it is self inflicted and the runtime will laugh at you.
Note that in .NET Core, the runtime will sometimes stop you doing this, because of JIT optimisations that would become invalid if you did. But if it doesn't here: fine.
Note: you used to be able to change string.Empty
via reflection. Imagine how well that ended :)
Why is it possible to change the value of a readonly field but not of a const using reflection?
Because const
fields are 'set' at compile time, i.e. the compiler replaces the const
with the given value during compilation. As a result of the way const
values work, their values are copied into every assembly that uses them. Whereas readonly
fields are evaluated at runtime.
Related Topics
ASP.NET MVC Custom Error Handling Application_Error Global.Asax
How to Abort a Task Like Aborting a Thread (Thread.Abort Method)
Differencebetween a Shared Project and a Class Library in Visual Studio 2015
Fixed Size Queue Which Automatically Dequeues Old Values Upon New Enques
Parallel.Foreach VS Task.Factory.Startnew
ASP.NET MVC $.Post Call Returning String...Need Help with Format for Jqgrid
Change a Web.Config Programmatically with C# (.Net)
Linq - Left Join, Group By, and Count
Selectsinglenode Returns Null When Tag Contains Xmlnamespace
Does Mono Support System.Drawing and System.Drawing.Printing
Deserialize JSON with Known and Unknown Fields
How to Embed a Text File in a .Net Assembly
How to Configure Socket Connect Timeout
How to Serialize a Dictionary as Part of Its Parent Object Using JSON.Net
The Cast to Value Type 'Int32' Failed Because the Materialized Value Is Null