Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

250
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda