DEV Community

6 Options to Implement Auto-Implemented Properties

Carl Layton on February 22, 2024

Introduction In this post, I show 6 ways to implement auto-implemented properties in C#. An auto-implemented property is a short-hand wa...
Collapse
 
peledzohar profile image
Zohar Peled

Using private set doesn't mean the property can only be set via the constructor. It can be set from anywhere inside the instance. This is still a mutable property, only you now have full control over its set calls:

public class Person
{
    public string Name {get; private set;}
    public void ChangeName(string newName) => Name = newName;
}
Enter fullscreen mode Exit fullscreen mode

If you want an immutable property, you can use a get-only property (meaning it has to be initialized either directly or from a constructor) or a get/init property (so it can also be initialized from object initialization:

public class Person
{
    public Person(string firstName) => FirstName = firstName;
    public string FirstName {get;}
    public string MiddleName {get;} = "";
    public string LastName {get;init;}
}

var me = new Person("Zohar") {LastName = "Peled"};
Enter fullscreen mode Exit fullscreen mode