How to assign value to readonly field in abstract class?

I have a field in a base abstract class. I want to make this field read-only so that its value does not change after the initialization of the child class.

But an abstract class cannot have a constructor, and readonly can only be initialized from the constructor.

How to do it?

+4
source share
3 answers

You can, for example, call the constructor of the base class from the constructor of the child class as follows:

Readonly field and constructor in the base class:

public readonly int MyInt; protected TheBaseClass(int myInt) { this.MyInt = myInt; } 

Constructors in a child class:

 public TheChildClass() : base(42) { } public TheChildClass(int i) : base(i) { } 
+9
source

abstract class may have a constructor.

 public abstract class MyAbstract { protected readonly string SomeField; public MyAbstract() { SomeField = "Some"; } } public abstract class MyInheited { public MyInheited(): base() { } } 

If I were you, I would have a field , not just a protected field , but expose it as a public readonly property

+5
source

CAN abstract classes may have a constructor; they may simply not be run.

+2
source

Source: https://habr.com/ru/post/1345097/


All Articles