1- Use readonly fields and initialize them through the constructor.
2- Avoid setters for properties.
3- Mark the class as sealed to prevent inheritance (optional).
Here’s a simple example:
public sealed class ImmutablePerson
{
public readonly string FirstName { get; }
public readonly string LastName { get; }
public ImmutablePerson(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public string GetFullName()
{
return $"{FirstName} {LastName}"
}
}
var person = new ImmutablePerson("John", "Doe");
Console.WriteLine(person.GetFullName());
In this example: 1- The FirstName and LastName properties are read-only.
2- The only way to set FirstName and LastName is through the constructor.
3- The class is sealed to prevent modification through inheritance.
readonly used on a property Remove it — properties can't be readonly
ReplyDeletepublic sealed class ImmutablePerson
ReplyDelete{
public string FirstName { get; }
public string LastName { get; }
public ImmutablePerson(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public string GetFullName()
{
return $"{FirstName} {LastName}";
}
}