Question

① In following C# code, CS1729 occurs but I understand that CS0122 would be more appropriate.

namespace A
{
  class Program
  {
    static void Main()
    {
      Test test = new Test(1);
    }
  }
  class Test
  {
    Test(int i) { }
  }
}

CS1729: 'A.Test' does not contain a constructor that takes 1 arguments

CS0122: 'A.Test.Test(int) is inaccessible due to its protection level'

② In following C# code, CS0122 occurs but I understand that CS1729 would be more appropriate

namespace A
{
  class Program
  {
    static void Main()
    {
      Test test = new Test();
    }
  }
  class Test
  {
    Test(int i) { }
  }
}   

CS0122: 'A.Test.Test(int) is inaccessible due to its protection level'

CS1729: 'A.Test' does not contain a constructor that takes 0 arguments

Question: Is there any reason why CS0122 and CS1729 are swapped in ① and ② or is this C# compiler bug ?

P.S.: Errors in ① and ② can be reproduced with Microsoft Visual C# 2010 Compiler version 4.030319.1.

Was it helpful?

Solution

Full disclosure: I work on the C# team at Microsoft.

Diagnostic reporting from a compiler is a tricky business! We spend a lot of time trying to ensure that the "best" diagnostic is reported for a particular error condition. However, this sometimes requires taking heuristics into account, and we don't always get that right. In this case, as @Henrik Holterman points out, both errors are reasonable (at least for the second case).

The first example is clearly a bug, though it's of low severity. After all, it's still an error with a somewhat "correct" (I'm being a bit gracious here) diagnostic. In the second example, both errors are correct, but the compiler failed to pick the "best", and hopefully, the most helpful diagnostic.

With the Roslyn C# compiler, we've had an opportunity to take a fresh look at our diagnostic reporting and make better choices. For these particular examples, the Roslyn compilers do in fact produce the errors that you were expecting. In the first example, CS0122 is reported, and in the second case, CS1729 is reported. So, you can rest assured that this is already fixed in a future release.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top