Monday, July 23, 2007

C# Namespaces

Warning: Somewhat serious C# geekage lies just yonder. It is geared towards those of you who are software developers working with C#, especially if you're coming from a few years of Java coding. If this is not you, you're welcome to read on, but you'll probably be bored.

I just went through some pain trying to figure out why ReSharper was telling me that the namespace of a particular class was wrong. The specific error I was getting was "namespace does not correspond to file location". I noticed that the directory name the source file was in did not match the namespace. I liked the namespace, so I decided that once the project was in a somewhat stable state I would go back and clean up the directory structure.

So, once the project was in a somewhat stable state, I cleaned up the directory structure (not a completely trivial task, as I had to coordinate the solution with the project files and keep the revision control system happy), and was surprised to find that ReSharper was still telling me the namespace was wrong. I tried different names. I tried adding dots. I tried removing dots. I tried searching the ReSharper support forums. It was all to no avail. Then I dug through the .cproj file itself, and found that it contained an attribute indicating a root namespace for the assembly.

It then all fell into place: I was treating namespaces just like packages in Java. Although they're close, they're not the same. In Java, the package name must match the directory name. In C#, it appears it just has to match (or be a subspace of) the root namespace for the project.

This is one of those cases where, having Java experience hindered rather than helped my learning of C#. Of course, if the ReSharper error message had mentioned the root namespace rather than file location, that would have been helpful as well. Perhaps the ReSharper developers are coming from a Java background as well. But I can't get too annoyed with them because ReSharper is a fantastic tool.

3 comments:

Ilya Ryzhenkov said...

Actually, ReSharper suggests namespace as "Default Project Namespace" plus "relative folder path". You can switch the warning altogether in options. You can tune it a bit using properties of the folder in solution explorer - see "Namespace Provider" property.
Organizing namespaces this way is normal practice in C# world, and VS itself does this way - try to add new class using VS and see default generated namespace. ReSharper's is a bit smarter, though ;)

Владимир said...

Thank you for explanations, it really bothered me. (I bought ReSharper recently and I love it.)

Anonymous said...

Thanks..this saved me a lot of time