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

257
Views
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
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!