I'm looking for an explanation as to why unused constructor overloads that contain an unreferenced class would create a compile time error when using the other constructors in that class will build and run correctly.
Here's some example code that demonstrates the issue.
// Console Project - references CL1 but not CL2
static void Main(String[] args)
{
var rc1 = new ReferencedClass(); // compiles and runs
var rc2 = new ReferencedClass(1); // wont compile. Needs CL2 reference
var rc3 = new ReferencedClass(0, ""); // compiles and runs
}
// Class Library 1 (CL1) - references CL2
public class ReferencedClass
{
private UnreferencedClass _unreferencedClass;
public ReferencedClass()
{
_unreferencedClass = new UnreferencedClass();
}
public ReferencedClass(Int32 id)
{
_unreferencedClass = new UnreferencedClass();
}
public ReferencedClass(UnreferencedClass uf)
{
_unreferencedClass = uf;
}
public ReferencedClass(Int32 id, String name)
{
_unreferencedClass = new UnreferencedClass();
}
}
// Class Library 2 (CL2)
public class UnreferencedClass {}
In all cases, the constructor with the unreferenced class isn't used so why does the build fail on the Int32 overloaded constructor?
The compiler needs the type during overload resolution.
See here: https://connect.microsoft.com/VisualStudio/feedback/details/817276/error-cs0012-the-type-is-defined-in-an-assembly-that-is-not-referenced-issued-for-an-extension-method-that-is-not-used
Paraphrased answer from the connect link:
In the course of ascribing meaning to the name "ReferencedClass" in your program, the compiler follows its lookup rules to determine the set of methods that it must examine. Both constructors taking one argument are examined as part of overload resolution. In order to determine which one makes sense for the call, the compiler must understand all of the types in the constructors' signatures. If some types are not found due to missing references, the compiler does not simply discard the candidate but instead requires that the user supply the missing references.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With