So when designing an immutable class should it use get properties as such
public sealed class Person
{
readonly string name;
readonly int age;
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
public string Name
{
get { return name; }
}
public int Age
{
get { return age; }
}
}
Or is it valid to expose public readonly fields
public sealed class Person
{
public readonly string Name;
public readonly int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
While both options will leave you with objects whose fields cannot be changed from the outside, the same guidelines apply for immutable objects as otherwise:
Using properties instead of publicly exposing your fields is still an advantage; you are not checking any input values, but still, future versions of your type might compute some of the values rather than read them directly from an internal field. By using properties, you hide that implementation detail and hence increase your flexibility for future changes.