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?
>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.