I have a field in base abstract class. I want to make this field readonly so that its value do not changed after child class has been initialized.
But abstract class cannot have constructor and readonly can only be initialized from constructor.
How to achieve this?
Code consuming a ReadOnly property cannot set its value. But code that has access to the underlying storage can assign or change the value at any time. You can assign a value to a ReadOnly variable only in its declaration or in the constructor of a class or structure in which it is defined.
Use the readonly keyword in C#You cannot change the value or reassign a value to a readonly variable or object in any other method except the constructor.
In c#, we can create the Read-only fields using readonly keyword. In c#, you can initialize the readonly fields either at the declaration or in a constructor. The readonly field values will evaluate during the run time in c#.
You could for instance call a the constructor of your base class from the child class constructor like this:
Readonly field and constructor in base class:
public readonly int MyInt;
protected TheBaseClass(int myInt)
{
this.MyInt = myInt;
}
Constructors in child class:
public TheChildClass() : base(42)
{
}
public TheChildClass(int i) : base(i)
{
}
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