I have an abstract class and I\'d like to initialize a readonly field in its protected constructor. I\'d like this readonly field to be available in derived classes.
Using reflection you can overwrite the readonly field with ease. Using a property makes it harder because the field is hidden ( You can still do it ). So i would prefer a property which is anyway the cleaner because you can change the getter without any issues.
If you're thinking about performance: Properties are inlined most times.
class Program
{
static void Main(string[] args)
{
Test t = new Test();
t.OverrideReadonly("TestField", 5);
t.OverrideReadonly("TestField2", 6);
t.OverrideReadonly("TestField3", new Test());
}
}
class Test
{
protected readonly Int32 TestField = 1;
protected readonly Int32 TestField2 = 2;
protected readonly Test TestField3 = null;
public void OverrideReadonly(String fieldName, Object value)
{
FieldInfo field = typeof(Test).GetField(fieldName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
field.SetValue(this, value);
}
}