Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

269
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda