Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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;
    }
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!