How can I supply a read-only property's value by calling a constructor?

Viewed 63

I have a Book class with a constructor which has a title parameter:

public class Book
    public Book (string title)
        {
           this.Title = title;
        }

I need to supply a Title's (read-only property) value by calling the Book constructor. I tried the following but not sure if this is correct since as I understood read-only property should only have a getter.

public string Title { get; private set {} }

I need Help to Finalize / correct this code block. Thank you in advance.

4 Answers

As you have currently defined Title, it is able to be set from anywhere inside Book. That is to say, it is not read-only, merely private.

To make it read-only (in a similar way to the readonly keyword on fields) you can simply declare it like this:

public string Title { get; }

And then you can use the constructor code you currently have to initialize it:

public Book (string title)
{
    this.Title = title;
}

As Ran notes in the other answer, C# 9 has introduced the concept of the init modifier. The difference with init is that, while the property can still only be set once, it can be initialized from outside the constructor. This is useful if you want to use the object initializer pattern, for example.

Any read only field can be set in the constructor, where after the constructing is done the field will become immutable. In other words, you don't need to do anything fancy, the constructor will handle it.

Just do an interface with your

public string Title { get; }

and then implement this interface into your class/classes & do a simple field (outside the constructor, over your method):

public string Title => "xyz"; //(or string.Empty)
Related