I have a class with two read-only fields that are being set in the constructor. I have a derived class that would like to set these to different values in the constructor; however, trying to do so results in a CS1091 (A readonly field cannot be assigned to (except in a constructor or a variable initializer) error.
I don't see why this is - I am assigning to the fields in a constructor. Just not the one of the class where they're defined.
Is there some subtle syntax issue that I'm missing, or is this just not possible?
(There's ways around it if this isn't possible - probably a protected virtual property without a setter, and private readonly backing fields; syntactically it's not going to be as clean, however, so I wanted to avoid them if I can.)
public class BaseClass
{
protected readonly ushort OffsetRoutine;
protected readonly ushort OffsetString;
public BaseClass()
{
this.OffsetRoutine = this.GetWord(Addresses.Header.OffsetRoutine);
this.OffsetString = this.GetWord(Addresses.Header.OffsetString);
}
protected ushort GetWord(byte address)
{
// Chosen by fair dice roll on a d100.
return 42;
}
}
public class DerivedClass : BaseClass
{
public DerivedClass()
: base()
{
this.OffsetRoutine = 0;
this.OffsetString = 0;
}
}
The other answers are not providing a key detail - setting a readonly field is allowed ONLY in the declaration OR a constructor of the same class. This is just one of the differences between readonly and const. The const modifier does not allow you to set the field in a constructor - only in the declaration. So setting the readonly in a derived class is simply not allowed since the field is not in the same class. I assume you don't need workarounds as you seemed to know how to go about it if necessary, and there are other answers discussing that. From MSDN (http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx):
When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
Just a few examples:
public class A
{
protected const string constString = "Test"; //Allowed
protected readonly string readonlyString = "Test"; //Allowed
public A(){
constString = "Test"; //Not allowed
readonlyString = "Test"; //Allowed
}
}
public class B: A
{
public B(){
constString = "Test"; //Not allowed
readonlyString = "Test"; //Not allowed
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With