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

260
Visualizações
How are Optional attribute and nullable references supposed to work together?

I am a big fan of C# nullable references and we enable them in all our new projects. Recently I was reviewing a PR from a co-worker and found that [Optional] attribute was used next to the reference parameter with no default value being specified. This would mean that we are breaking "nullable reference constraint" as the default value for the function argument would be null, even though the argument is not marked as nullable. Please see the example code below:

class Program
{
    internal class Data
    {
        internal int Count { get; set; } = 3;
    }

    static void Main(string[] args)
    {
        BadUse();
        GoodUse();
    }

    static void BadUse([Optional] Data data) => Console.WriteLine($"Data: ${data.Count}");

    static void BadUse2([Optional, DefaultParameterValue(null)] Data data) => Console.WriteLine($"Data: ${data.Count}");

    static void GoodUse(Data? data = null) => Console.WriteLine($"Data: ${data?.Count}");
}

As you can see the method BadUse above is incorrect and will cause null reference exception without any warning nor compilation error. Naturally, we use the more readable optional argument pattern as in GoodUse. I wonder if this is a bug in C# compiler or I am missing something here? I would expect to see compilation error or at least some warning. Note that when the DefaultParameterValue attribute is used in BadUse2 we get the expected "CS8602 Dereference of a possibly null reference".

over 4 years ago · Santiago Trujillo
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