2

Is this a hole in C# 8's NNR checks?

public struct V
{
    private readonly double[] data;

    public V(int size) => data = new double[size];

    public int Length => data.Length;
}

var v = new V();
Console.WriteLine(v.Length);

I thought the compiler should have emitted a warning in this case, when using the default constructor. Yes, I know there are more cases when the "default constructor" is implicitly "used", but this case is the easiest one.

Is there anything that can be done in C# 8 about this?

  • 2
    Open an issue on the compiler repository on GitHub if you have an actual concern, but I can tell you that structs are different beasts due to their implicit empty constructor. I believe the code analysis component assumes you instantiate it with the non-default constructor, and that the default constructor is only used as a temporary placeholder (ie in arrays). – Blindy Jul 14 '20 at 15:04
  • What is the issue with your code? – Pavel Anikhouski Jul 14 '20 at 15:13
  • @PavelAnikhouski Here the array is never created... It would be using `var v = new V(10);` but the `new V()` does nothing thus `data` is `null`, even in C#8 apparently (I have VS2017). –  Jul 14 '20 at 16:01
  • @IanMarteens Does it do that for a class too ? Have you checked the VS or project compiler settings ? –  Jul 14 '20 at 16:08
  • 1
    @OlivierRogier With a class, it asks for a parameterless constructor, and when added, it complaints about the field not being initialized. – Ian Marteens Jul 14 '20 at 16:15
  • @Blindy, that's what I'll do. I just wanted to check first if I was missing something. – Ian Marteens Jul 14 '20 at 16:18

0 Answers0