Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign value to readonly field in an abstract class?

Tags:

c#

class

abstract

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?

like image 445
OnTheFly Avatar asked Mar 24 '11 14:03

OnTheFly


People also ask

How do I change values in readonly?

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.

Can we change the value of readonly in C#?

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.

How do you call a readonly property in C#?

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#.


1 Answers

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)
{
}
like image 78
Julian Avatar answered Oct 26 '22 23:10

Julian