Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do array elements seem to escape null checks?

Apparently non-nullable is the new default so I went with it. Consider the following piece of code:

public class C { }
        
public static C f()
{
    return null;
}

The compiler warns for a possible null reference return. But if I write instead:

public static C f()
{
    C[] a = new C[10];
    return a[0]; // null
}

Then the compiler stays silent. I checked that the value returned is actually null. Is this just a weakness of the inference engine?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your array is declared as type C[] rather than C?[] – so the compiler expects that you know what you’re doing and will populate the elements so they’re non-null. It doesn’t take into account that the default element values will be null. Detecting code to fully populate the array before reading any values would be extremely difficult or infeasible.

Whether you consider this a "weakness of the inference engine" or not is more of a matter of opinion; but basically you should be careful with arrays.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading