Here's the scenario. I create a new class library project in Visual Studio, add some classes. Then at some point I decide that I need some class to be marked with System.Runtime.Serialization.DataContractAttribute
and I write the following:
[DataContract]
public class MyDataContractClass {}
and when I hit compile I see the following error:
error CS0246: The type or namespace name 'DataMember' could not be found (are you missing a using directive or an assembly reference?)
Okay, the problem is I forgot to add using
directive to make the class visible. I add
using System.Runtime.Serialization;
to the same file above the class but the problem doesn't go away until I add a reference to System.Runtime.Serialization
in the Project Explorer.
This is very confusing. Why do I have to add the same thing two times in different places and see the same error message regardless of which of the two steps I missed?
My question is the following. Is this just badly designed error diagnostics or is there some fundamental reason why missing any of the two above steps leads to the same error emitted by the C# compiler?
You're not doing the same thing twice. Any assembly may contain types in any namespace. A using
statement is just a shortcut to referencing types in a namespace - and those types could be supplied by any assembly.
The general convention in system supplied assemblies is that assemblies with the same name as a namespace will contain a large number of types within that namespace - but there's no way for the compiler to know which assembly you've forgotten to reference if it can't resolve a type name - it can't even know (until you add the right assembly) that DataContract is in the System.Runtime.Serialization
namespace.
To have it improve the diagnostics as you want, it would need to, when compiling: