Compilation errors in Reference.cs after adding a Service Reference caused by multi-part namespace

Simon Needham picture Simon Needham · May 19, 2011 · Viewed 17.4k times · Source

I hit this weird namespace issue when adding my first 'Service Reference' to a client project in Visual Studio 2010.

If my project's default namespace uses two or more parts, e.g. MyCompany.MyApp then when adding a Service Reference a Reference.cs file is created containing the namespace MyCompany.MyApp.ServiceReferenceName with a lot of auto-gen code with fully qualified names, e.g. System.SerializableAttribute, System.Runtime.Serialization.DataContractAttribute.

The Reference.cs file will be full of compilation errors because the compiler starts treating the System namespace as sub member of the MyCompany.MyApp namespace. You get an awful lot of errors along the lines of:

The type or namespace name 'Runtime' does not exist in the namespace 'MyCompany.MyApp.System'...

If I amend the namespace at the top of the Reference.cs file to something simple, e.g. MyCompanyMyApp.ServiceRefernceName then the compiler behaves and recognises the System namespace references as decleration of .net's System namespace.

I'm using a different workaround for now as I really want to keep my multi-part namespaces. My current alternative is to append global:: in front of the System namespace references to force the complier to do the right thing. In fact, if the 'Add Service Reference' wizard uses T4 templates I may just amend those to embed my workaround at the source.

Questions

I'd really like to understand what's going on here and why a multi-part namespace causes this issue. Presumably there's more to namespaces than I thought. Secondly, would really like to work out a better solution than performing a global Find/Replace every time I add a Service Reference or mucking around with some T4 templates.

Answer

Flory picture Flory · Dec 12, 2012

I found the answer here somewhat unclear, so I thought I would add this as an example (I would do it in the comments but it looks better here):

So I have this as my default namespace:

namespace RelatedData.Loader

But I also add a class named:

 public class RelatedData
{
}

Because the class name matches a portion of the namespace when it generates your proxy with Add Service Reference it gets confused.

The answer here was to rename my class:

 public class RelatedDataItem