The Daily Parker

Politics, Weather, Photography, and the Dog

N is for Namespace

Blogging A to ZDay 14 of the Blogging A-to-Z challenge brings us to namespaces.

Simply put, a namespace puts logical scope around a group of types. In .NET and in other languages, types typically belong to namespaces two or three levels down.

Look at the sample code for this series. You'll notice that all of the types have a scope around them something like this:

namespace InnerDrive.Application.Module
{
}

(In some languages it's customary to use the complete domain name of the organization creating the code as part of the namespace and to use alternate letter cases. If I were writing Java, for example, that would look like com.inner-drive.application.module.)

Every type defined in the namespace belongs to only that namespace. If I defined a type in the example namespace above called Foo, the fully-qualified type name would be InnerDrive.Application.Module.Foo. Because using FQTNs requires a lot of typing and makes code harder to read, .NET gives you another use of the namespace keyword:

using InnerDrive.Application.Module;

namespace InnerDrive.Application.OtherModule
{
	public class Bar
	{
		public void Initialize() 
		{
			// var foo = new InnerDrive.Application.Module.Foo() is not required
			var foo = new Foo();
			foo.Start();
		}
	}
}

Also, that Bar class belongs only to the InnerDrive.Application.OtherModule namespace, so another developer could create another Bar class in her own namespace without needing to worry about mine.

Comments (2) -

  • David Harper

    4/16/2018 2:36:23 PM +00:00 |

    In Java, the namespace also acts as a way of controlling access to methods and fields of a class.  For example, a method or field declared with no modifier (i.e. without any of the keywords 'public', 'protected' or 'private') can be accessed by other classes in the same package, but not by classes in another package.  I'm guessing that something similar applies in .NET

  • The Daily Parker

    4/16/2018 2:45:43 PM +00:00 |

    David,

    That behavior sounds more like the internal modifier in C#. Namespaces in C# don't change access to types; they just group types. The internal modifier restricts access to types within the same assembly, even if the types are in different namespaces.

Comments are closed