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

452
Visualizações
C#10 nullable pattern: how to tell the compiler I set the non-nullable property in the constructor indirectly?

Consider an example:

class Test {

    string S { get; set; }

    public Test() {
        Init();
    }

    private void Init() {
        S = "hello";
    }
 
}

Using nullable C# project feature, this sample will trigger a compiler warning:

Warning CS8618 Non-nullable property 'S' must contain a non-null value when exiting the constructor. Consider declaring the property as nullable.

However, the property DOES contain non-null value when exiting the constructor, it's just not set directly in the constructor, but indirectly in a method that is unconditionally called from the constructor.

This example shows clearly that there is no possibility for the S property to ever be null. When an instance of the Test class is created, the Init() method is called unconditionally, so the S property is ALWAYS set to "hello".

Of course, this warning can be suppressed in code, but this looks just fugly. Is it a better way to tell the compiler I really did set the S property to a non-null value elsewhere?

BTW, if you really wonder WHY to set values in the constructor indirectly, let's consider there is another derived property D of Derived type. To create an instance of Derived the string must be parsed first and we don't want to parse the string each time we read the D property.

So, the more realistic code would look more like this:

class Test {

    public string S { 
        get => _S;
        set => D = new Derived(_S = value);
    }

    public Derived D { get; private set; }

    public Test(string s) => D = new Derived(_S = s);

    private string _S;
 
}

As you can see, both S and D are set to non-null values when exiting the constructor. Yet the code still triggers the compiler warning CS8618.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Use MemberNotNullAttribute to mark your function:

using System.Diagnostics.CodeAnalysis;

class Test
{

    string S { get; set; }

    public Test()
    {
        Init();
    }

    [MemberNotNull(nameof(S))]
    private void Init()
    {
        S = "hello";
    }

}

The compiler will now complain if you do not initialize S in Init:

enter image description here

See more scenarios in this article: Attributes for null-state static analysis

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