Travis J
Travis J

Reputation: 82337

Why don't similar namespaced classes share using directives?

When adding a new class into a namespace this is what I get (this is in an mvc3 project)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Foo.Models
{
 public class Bar
 {
 }
}

In the namespace Foo.Models there are other classes. However, it is nice to separate content by placing them in different .cs locations. I think that is fairly standard. I know the compiler works its magic to compose all these later anyway. Which is kind of where my question arose from. If the namespace is composed later on, then why is there a requirement to always be redefining what the class is using? If it is already available somewhere in the namespace, then should it be necessary to say using System; in every .cs file defining a class inside of the namespace? Can someone explain this a little for me, and also perhaps shed some light on a possible way to do implement this in a way where I define all of the using cases for a namespace once and then any classes added to that namespace inherently have access to those.

Upvotes: 0

Views: 96

Answers (1)

Eric J.
Eric J.

Reputation: 150238

The using statements are scoped to the particular .cs file you are working with.

They simply provide a convenient shortcut in the context of that class file that allows you to use the names of classes only, rather than fully qualifying class names everywhere you use them.

Namespaces exist because different teams will inevitably use the same class name for different classes (I wonder how many Util classes are out there).

You may have two different classes in your project that want to use different objects with the same name. The ability to have different using statements in each file lets you do that conveniently.

Note that you can always edit the template for new classes to pre-populate the using statements you need in all of your classes.

Upvotes: 3

Related Questions