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.
CodePudding user response:
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.
CodePudding user response:
C# 9 introduces the init
keyword which is a variation of set
, which allows us to do it. The init
accessor is actually a variant of the set
accessor which can only be called during object initialization
public class Book
{
public string Title { get; init };
}
More about init
- https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init
CodePudding user response:
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.
CodePudding user response:
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)