Combine property setter "init and private" (C#9)

Viewed 614

I ask about the new C#9-feature "init property setter". Below an example of it:

public class MyClass
{
    public int Id { get; init; }
    public int Name { get; init; }
    public int Position { get; init; }
}

My question is how I can update the value of 'Position' after initialize. I want something like this:

public class MyClass
{
    public int Id { get; init; }
    public int Name { get; init; }
    public int Position { get; init + private set; }

    public void MoveMyClass(int newPositionIndex)
    {
        // Some business code...
        Position = newPositionIndex;
    }
}

In my real world project an instance of MyClass is initialized by entity framework. Then I call some business methods on it. The rule is that only business methods are allowed to set values on properties, so I want at least private setters. But if I have private setters then entity framework cannot initialize the properties.

1 Answers

It seems that this feature is not available for auto-properties in C#9.

To solve this issue I combine init with the full property style (instead auto property). Maybee C#10 or later would support such an access modifier.

public class MyClass
{
    private int _position;

    public int Id { get; init; }
    public int Name { get; init; }
    public int Position { get => _position; init => _position = value; }

    public void MoveMyClass(int newPositionIndex)
    {
        // Some business code...
        _position = newPositionIndex;
    }
}
Related