I have a class that's name is the same as the namespace is is contained within:
Class File ReadModel.cs
namespace App.Core.ReadModel
{
public class ReadModel
{
}
}
Class File MyClass.cs
using App.Core.ReadModel; // this does not work
namespace Something
{
// using App.Core.ReadModel (Works if I un-comment)
public class MyClass
{
public void test()
{
var x = new ReadModel();
}
}
}
When trying to instantiate the class, even when trying to add a using directive at the top, the compiler is still unable to resolve the class. HOWEVER, if I put the using statements nested within the namespace, it works fine.
Can someone pls explain why this works? This is a new feature I've just discovered.
The error is: App.Core.ReadModel is a namespace but is used like a type
The difference between
using System ;
using Foo.Bar ;
namespace My.Widget.Tools
{
public class MySpecialTool
{
...
}
}
and
using System ;
namespace My.Widget.Tools
{
using Foo.Bar ;
public class MySpecialTool
{
...
}
}
is that in the first case, the directive using Foo.Bar ; causes the objects in the namespace Foo.Bar to be imported into the unnamed (global) namespace for the compilation unit. In the second case, the using directive imports the objects in the namespace Foo.Bar into the namespace My.Widget.Tools.
The difference has to do with search order in resolving unqualified references.
Unqualified references are resolved by first searching within the enclosing named namespace. If the reference is not resolved, then the unnamed (global) namespace for the compilation unit is searched.
Consider the case where the above namespace Foo.Bar contains a visible class that conflicts with a class contained in the System namespace.
In the first case, where the Foo.Bar namespace has been loading into the global namespace, you'll get an error regarding an ambiguous reference if you try to reference the conflicting object: it will search the enclosing namespace first, on not finding it, it will then look into the global namespace and find multiple objects and whine.
In the second case, the enclosing namespace is searched first, on finding an object of the desired name, the unqualified reference is resolved and the compiler is happy: no conflict.
Note that you can coerce the search order to the global namespace by qualifying an object reference with the global:: prefix. You can also define your own aliases with the using directive, either for a namespace:
using io = System.IO ;
or for a type:
using IntList = System.Collections.Generic.List<int> ;
the caveat with defining an alias for the namespace is that you then have to use the alias to resolve a reference. An alias defined for a type just gives you a [perhaps] shorthand way of naming the type. Probably more useful for generics than anything else. I don't see a lot of value in doing something like:
using Row = System.Data.DataRow ;
outside of writing obfuscated C#.
See also this question: Should 'using' statements be inside or outside the namespace?
ยง16 of ISO/IEC 23270:2006 (Information technology -- Programming languages -- C#) will tell you far more than you ever wanted to know about namespaces and using directives.
See also this MSDN piece on namespace aliases: http://msdn.microsoft.com/en-us/library/c3ay4x3d(v=vs.80).aspx
Edit again:
Nicholas answered your revised question very nicely. Please see his answer:
Visual Studio unable to resolve class name unless using nested using block
EDIT:
Using have to be at the top of the file. Move the using above the first namespace.
Example:
namespace App.Core.ReadModel
{
public class ReadModel
{
}
}
using App.Core.ReadModel; // cannot be placed here. Must be at top of file.
namespace App
{
public class Program
{
public static Main()
{
var obj = new ReadModel();
}
}
}
Original Answer (irrelevant to question):
Option 1: Rename Namespace
namespace App.Core.IO
{
public class ReadModel
{
}
}
Option 2: Use an Alias
using MyReadModel = App.Core.ReadModel.ReadModel;
public class Program
{
public static void Main()
{
var obj = new MyReadModel();
}
}
Option 3: Qualify Type Name
public class Program
{
public static void Main()
{
var obj = new App.Core.ReadModel.ReadModel();
}
}
Related
Where or when would one would use namespace aliasing like
using someOtherName = System.Timers.Timer;
It seems to me that it would just add more confusion to understanding the language.
That is a type alias, not a namespace alias; it is useful to disambiguate - for example, against:
using WinformTimer = System.Windows.Forms.Timer;
using ThreadingTimer = System.Threading.Timer;
(ps: thanks for the choice of Timer ;-p)
Otherwise, if you use both System.Windows.Forms.Timer and System.Timers.Timer in the same file you'd have to keep giving the full names (since Timer could be confusing).
It also plays a part with extern aliases for using types with the same fully-qualified type name from different assemblies - rare, but useful to be supported.
Actually, I can see another use: when you want quick access to a type, but don't want to use a regular using because you can't import some conflicting extension methods... a bit convoluted, but... here's an example...
namespace RealCode {
//using Foo; // can't use this - it breaks DoSomething
using Handy = Foo.Handy;
using Bar;
static class Program {
static void Main() {
Handy h = new Handy(); // prove available
string test = "abc";
test.DoSomething(); // prove available
}
}
}
namespace Foo {
static class TypeOne {
public static void DoSomething(this string value) { }
}
class Handy {}
}
namespace Bar {
static class TypeTwo {
public static void DoSomething(this string value) { }
}
}
I use it when I've got multiple namespaces with conflicting sub namespaces and/or object names you could just do something like [as an example]:
using src = Namespace1.Subspace.DataAccessObjects;
using dst = Namespace2.Subspace.DataAccessObjects;
...
src.DataObject source = new src.DataObject();
dst.DataObject destination = new dst.DataObject();
Which would otherwise have to be written:
Namespace1.Subspace.DataAccessObjects.DataObject source =
new Namespace1.Subspace.DataAccessObjects.DataObject();
Namespace2.Subspace.DataAccessObjects.DataObject dstination =
new Namespace2.Subspace.DataAccessObjects.DataObject();
It saves a ton of typing and can be used to make code a lot easier to read.
In addition to the examples mentioned, type aliases (rather than namespace aliases) can be handy when repeatedly referring to generic types:
Dictionary<string, SomeClassWithALongName> foo = new Dictionary<string, SomeClassWithALongName>();
private void DoStuff(Dictionary<string, SomeClassWithALongName> dict) {}
Versus:
using FooDict = Dictionary<string, SomeClassWithALongName>;
FooDict foo = new FooDict();
private void DoStuff(FooDict dict) {}
Brevity.
There are fringe benefits to provide clarity between namespaces which share type names, but essentially it's just sugar.
I always use it in situations like this
using Utility = MyBaseNamespace.MySubNamsepace.Utility;
where Utility would otherwise have a different context (like MyBaseNamespace.MySubNamespace.MySubSubNamespace.Utility), but I expect/prefer Utility to always point to that one particular class.
It is very useful when you have multiple classes with the same name in multiple included namespaces. For example...
namespace Something.From.SomeCompanyA {
public class Foo {
/* ... */
}
}
namespace CompanyB.Makes.ThisOne {
public class Foo {
/* ... */
}
}
You can use aliases to make the compiler happy and to make things more clear for you and others on your team:
using CompanyA = Something.From.CompanyA;
using CompanyB = CompanyB.Makes.ThisOne;
/* ... */
CompanyA.Foo f = new CompanyA.Foo();
CompanyB.Foo x = new CompanyB.Foo();
We have defined namespace aliases for all of our namespaces. This makes it very easy to see where a class comes from, e.g:
using System.Web.WebControls;
// lots of other using statements
// contains the domain model for project X
using dom = Company.ProjectX.DomainModel;
// contains common web functionality
using web = Company.Web;
// etc.
and
// User from the domain model
dom.User user = new dom.User();
// Data transfer object
dto.User user = new dto.User();
// a global helper class
utl.SomeHelper.StaticMethod();
// a hyperlink with custom functionality
// (as opposed to System.Web.Controls.HyperLink)
web.HyperLink link = new web.HyperLink();
We have defined some guidelines how the aliases must be named and everyone is using them.
I find the aliases very useful in unit testing. When you are writing unit tests, it is a common practice to declare the subject to test as
MyClass myClassUT;
being myClassUT the subject Under Test. But what if you want to write unit tests for a static class with static methods? Then you can create an alias like this:
using MyStaticClassUT = Namespace.MyStaticClass;
Then you can write your unit tests like this:
public void Test()
{
var actual = MyStaticClassUT.Method();
var expected = ...
}
and you never loose sight of what the subject under test is.
In one way it is really handy while coding in Visual Studio.
Use-case: Let's say I've to use only few classes e.g. SqlConnection from a namespace System.Data. In normal course I'll import the System.Data.SqlClient namespace at the top of the *.cs file as shown below:
using System.Data;
Now look at my intellisense. It is heavily proliferated with whole lot of classes to choose from while typing in code editor. I'm not going to use whole bunch of classes at all:
So I would rather use an alias at the top of my *.cs file and get a clear intellisense view:
using SqlDataCon = System.Data.SqlClient.SqlConnection
Now look at my intellisense view. It is super-clear and super-clean.
One reason I know; It lets you use shorter names when you have name collisions from imported namespaces.
Example:
If you declared using System.Windows.Forms; and using System.Windows.Input; in the same file when you go to access ModifierKeys you might find that the name ModifierKeys is in both the System.Windows.Forms.Control and System.Windows.Input namespaces.
So by declaring using Input = System.Windows.Input; you can then get System.Windows.Input.ModifierKeys via Input.ModifierKeys.
I'm not a C# buff but aliasing namespace seems like "best practise" to me. That way you know what you're getting and still don't have to type too much more.
You can use them to modify a code very easily.
For example:
#if USE_DOUBLES
using BNumber = System.Double;
#else
using BNumber = System.Single;
#endif
public void BNumber DoStuff(BNumber n) {
// ...
}
public void BNumber DoStuff2(BNumber n) {
// ...
}
public void BNumber DoStuff3(BNumber n) {
// ...
}
By the simple change in of the directive you can decide if your whole code works in float or double.
This question already has answers here:
Importing nested namespaces automatically in C#
(7 answers)
Closed 7 years ago.
Whenever, I start a new project in C#, I get the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
Why does using System; not allow you to use the sub namespaces with just the one line? I'm looking for an underlying reason as to why this isn't allowed. In the example given in the answer by HuorSwords:
namespace First {
class A { }
}
namespace First.Second {
class A { }
}
I would still get an error if I do:
using First;
using First.Second;
function void Test()
{
A variable;
}
I would still have to differeniate between the two. So then why am I forced to declare both namespaces instead of just the one? Aside from potential ambiguity, is there any other reason why we have to declare each namespace like this?
Think about this situation:
namespace First {
class A { }
}
namespace First.Second {
class A { }
}
If the behavior could be as you propose, then when you reference First namespace declaring a using First; sentence, and declares a variable of class A, how the compiler can deduce what of your two A classes should be used?
You can reference any type without using any using sentence, just putting the full namespace reference when you declare the variable.
var firstA = new First.A();
var secondA = new First.Second.A();
Then, when you try to import two or more namespaces that contains classes equally named, the compiler raises an error in order you can specify what class should be used.
So here is a snippet I made where one namespace in inside another (B is inside A).
Usually when you use 'using SpaceA;' you can access all elements without typing SpaceA.
This is the case for class A, but I cannot see SpaceB without having to type SpaceA.SpaceB. Why is this?
Here is the code:
using System;
using SpaceA;
namespace SpaceA
{
class A
{
public A()
{
Console.WriteLine("A");
}
}
namespace SpaceB
{
public class B
{
public B()
{
Console.WriteLine("B");
}
}
}
}
namespace TestingCSharp
{
class Program
{
static void Main(string[] args)
{
//This does not work
SpaceB.B x = new SpaceB.B();
//This does work
SpaceA.SpaceB.B y = new SpaceA.SpaceB.B();
}
}
}
Usually when you use 'using SpaceA;' you can access all elements without typing SpaceA.
Only the direct types which are members of SpaceA. A namespace-or-type-name is never resolved using a namespace in a normal using directive and then another "subnamespace" in the name. Note that this has nothing to do with how the types are declared (in terms of having a nested namespace declaration or just namespace SpaceA.SpaceB) - another example would be:
using System;
...
Xml.Linq.XElement x = null; // Invalid
See section 3.8 of the C# 5 specification for the precise details of how names are resolved.
One slight difference to this is if you have a using alias directive for a namespace, at which point that can be used to look up other namespaces
using X = System.Xml;
...
X.Linq.XElement x = null; // Valid
I get compile error because the compiler thinks Path.Combine refers to my field, but I want it to refer to class System.IO.Path. Is there a good way to handle this other than always having to write the FQN like System.IO.Path.Combine()?
using System.IO;
class Foo
{
public string Path;
void Bar(){ Path.Combine("",""); } // compile error here
}
You can do this:
using IOPath = System.IO.Path;
Then in your code:
class Foo
{
public string Path;
void Bar(){ IOPath.Combine("",""); } // compile error here
}
Seperate your references:
this.Path = System.IO.Path.PathFunction();
I'd strongly suggest implying the System.IO namespace when using Path anywhere inside that class, because it's very difficult to tell the difference. Using the this. qualifier and the full namespace makes them distinct.
Where or when would one would use namespace aliasing like
using someOtherName = System.Timers.Timer;
It seems to me that it would just add more confusion to understanding the language.
That is a type alias, not a namespace alias; it is useful to disambiguate - for example, against:
using WinformTimer = System.Windows.Forms.Timer;
using ThreadingTimer = System.Threading.Timer;
(ps: thanks for the choice of Timer ;-p)
Otherwise, if you use both System.Windows.Forms.Timer and System.Timers.Timer in the same file you'd have to keep giving the full names (since Timer could be confusing).
It also plays a part with extern aliases for using types with the same fully-qualified type name from different assemblies - rare, but useful to be supported.
Actually, I can see another use: when you want quick access to a type, but don't want to use a regular using because you can't import some conflicting extension methods... a bit convoluted, but... here's an example...
namespace RealCode {
//using Foo; // can't use this - it breaks DoSomething
using Handy = Foo.Handy;
using Bar;
static class Program {
static void Main() {
Handy h = new Handy(); // prove available
string test = "abc";
test.DoSomething(); // prove available
}
}
}
namespace Foo {
static class TypeOne {
public static void DoSomething(this string value) { }
}
class Handy {}
}
namespace Bar {
static class TypeTwo {
public static void DoSomething(this string value) { }
}
}
I use it when I've got multiple namespaces with conflicting sub namespaces and/or object names you could just do something like [as an example]:
using src = Namespace1.Subspace.DataAccessObjects;
using dst = Namespace2.Subspace.DataAccessObjects;
...
src.DataObject source = new src.DataObject();
dst.DataObject destination = new dst.DataObject();
Which would otherwise have to be written:
Namespace1.Subspace.DataAccessObjects.DataObject source =
new Namespace1.Subspace.DataAccessObjects.DataObject();
Namespace2.Subspace.DataAccessObjects.DataObject dstination =
new Namespace2.Subspace.DataAccessObjects.DataObject();
It saves a ton of typing and can be used to make code a lot easier to read.
In addition to the examples mentioned, type aliases (rather than namespace aliases) can be handy when repeatedly referring to generic types:
Dictionary<string, SomeClassWithALongName> foo = new Dictionary<string, SomeClassWithALongName>();
private void DoStuff(Dictionary<string, SomeClassWithALongName> dict) {}
Versus:
using FooDict = Dictionary<string, SomeClassWithALongName>;
FooDict foo = new FooDict();
private void DoStuff(FooDict dict) {}
Brevity.
There are fringe benefits to provide clarity between namespaces which share type names, but essentially it's just sugar.
I always use it in situations like this
using Utility = MyBaseNamespace.MySubNamsepace.Utility;
where Utility would otherwise have a different context (like MyBaseNamespace.MySubNamespace.MySubSubNamespace.Utility), but I expect/prefer Utility to always point to that one particular class.
It is very useful when you have multiple classes with the same name in multiple included namespaces. For example...
namespace Something.From.SomeCompanyA {
public class Foo {
/* ... */
}
}
namespace CompanyB.Makes.ThisOne {
public class Foo {
/* ... */
}
}
You can use aliases to make the compiler happy and to make things more clear for you and others on your team:
using CompanyA = Something.From.CompanyA;
using CompanyB = CompanyB.Makes.ThisOne;
/* ... */
CompanyA.Foo f = new CompanyA.Foo();
CompanyB.Foo x = new CompanyB.Foo();
We have defined namespace aliases for all of our namespaces. This makes it very easy to see where a class comes from, e.g:
using System.Web.WebControls;
// lots of other using statements
// contains the domain model for project X
using dom = Company.ProjectX.DomainModel;
// contains common web functionality
using web = Company.Web;
// etc.
and
// User from the domain model
dom.User user = new dom.User();
// Data transfer object
dto.User user = new dto.User();
// a global helper class
utl.SomeHelper.StaticMethod();
// a hyperlink with custom functionality
// (as opposed to System.Web.Controls.HyperLink)
web.HyperLink link = new web.HyperLink();
We have defined some guidelines how the aliases must be named and everyone is using them.
I find the aliases very useful in unit testing. When you are writing unit tests, it is a common practice to declare the subject to test as
MyClass myClassUT;
being myClassUT the subject Under Test. But what if you want to write unit tests for a static class with static methods? Then you can create an alias like this:
using MyStaticClassUT = Namespace.MyStaticClass;
Then you can write your unit tests like this:
public void Test()
{
var actual = MyStaticClassUT.Method();
var expected = ...
}
and you never loose sight of what the subject under test is.
In one way it is really handy while coding in Visual Studio.
Use-case: Let's say I've to use only few classes e.g. SqlConnection from a namespace System.Data. In normal course I'll import the System.Data.SqlClient namespace at the top of the *.cs file as shown below:
using System.Data;
Now look at my intellisense. It is heavily proliferated with whole lot of classes to choose from while typing in code editor. I'm not going to use whole bunch of classes at all:
So I would rather use an alias at the top of my *.cs file and get a clear intellisense view:
using SqlDataCon = System.Data.SqlClient.SqlConnection
Now look at my intellisense view. It is super-clear and super-clean.
One reason I know; It lets you use shorter names when you have name collisions from imported namespaces.
Example:
If you declared using System.Windows.Forms; and using System.Windows.Input; in the same file when you go to access ModifierKeys you might find that the name ModifierKeys is in both the System.Windows.Forms.Control and System.Windows.Input namespaces.
So by declaring using Input = System.Windows.Input; you can then get System.Windows.Input.ModifierKeys via Input.ModifierKeys.
I'm not a C# buff but aliasing namespace seems like "best practise" to me. That way you know what you're getting and still don't have to type too much more.
You can use them to modify a code very easily.
For example:
#if USE_DOUBLES
using BNumber = System.Double;
#else
using BNumber = System.Single;
#endif
public void BNumber DoStuff(BNumber n) {
// ...
}
public void BNumber DoStuff2(BNumber n) {
// ...
}
public void BNumber DoStuff3(BNumber n) {
// ...
}
By the simple change in of the directive you can decide if your whole code works in float or double.