In C#, if I create a class with no namespace, what namespace will I use when trying to instantiate the class?
For example, assume main is...
namespace NamespaceTests
{
class Program
{
static void Main(string[] args)
{
}
}
}
... and assume my namespace-less class is ...
public class test
{
public string SayHello()
{
return "Hello World!";
}
}
... and assume I have another class by the same name, but having the default namespace...
namespace NamespaceTests
{
public class test
{
public string SayHello()
{
return "Hello Moon...";
}
}
}
... how would I modify main to include an instance of the namespace-less class and call 'SayHello' to retrieve the message "Hello World!"? Specifically, how would I fully qualify the namespace-less instance of class 'test', especially considering I may have another class also called 'test' but having a namespace, so I need to distinguish...
It's in the global namespace and can be referenced like this:
var x = new global::test();
Types not defined within a namespace will be in the global namespace.
The global contextual keyword, when it comes before the :: operator, refers to the global namespace, which is the default namespace for any C# program and is otherwise unnamed.
The following example shows how to use the global contextual keyword
to specify that the class TestApp is defined in the global namespace:
C# class TestClass : global::TestApp { }
In the addition to above answers, it is important to note, what all Type, regardless of its declaration location, has a "fully qualified name", which begins from "global::"
From "O'Relly. C# in a Nutshell":
All type names are converted to fully qualified names at compile time. Intermediate Language (IL) code contains no unqualified or partially qualified names
Related
I have inherited a large c# project. One of the classes has a namespace and class which share the same name. As a result when making an instance of the class i have to do this:
using xxx.existingName
IinterfaceName dog = new existingName.existingName();
Since the existing class has an interface i am able to avoid having existingName.existingName on the left of the =. Using var dog would also do this. However i also want to avoid existingName.existingName being used on the right hand side because it is less readable.
Is there any way to do this without renaming the existing code?
You could rename the class or the namespace via the using directive:
using ClassAlias = Test.Test;
using NamespaceAlias = Test;
public class Program
{
public static void Main()
{
ClassAlias a = new ClassAlias();
NamespaceAlias.Test t = new NamespaceAlias.Test();
}
}
namespace Test{
public class Test{}
}
You could use an alias to make this more readable(well, not with these names):
using AliasForName = existingName;
...
IinterfaceName dog = new AliasForName.existingName();
If the original author would have looked at this MSDN article, he would have used a different name in the first place:
X DO NOT use the same name for a namespace and a type in that
namespace . For example, do not use Debug as a namespace name and then
also provide a class named Debug in the same namespace. Several
compilers require such types to be fully qualified.
By the way, you should really apply capitaliation conventions.
I suspect this is a question which has been asked many times before but i haven't found one.
I normally use fully qualified namespaces if i don't use that type often in the file or i add using namaspacename at the top of the file to be able to write new ClassName().
But what if only a part of the full namespace was added ? Why can't the compiler find the type and throws an error?
Consider following class in a nested namespace:
namespace ns_1
{
namespace ns_1_1
{
public class Foo { }
}
}
So if i now want to initialize an instance of this class, it works in following ways:
using ns_1.ns_1_1;
public class Program
{
public Program()
{
// works, fully qualified namespace:
var foo = new ns_1.ns_1_1.Foo();
// works, because of using ns_1.ns_1_1:
foo = new Foo();
}
}
But following doesn't work:
using ns_1;
public class Program
{
public Program()
{
// doesn't work even if using ns_1 was added
var no_foo = new ns_1_1.Foo();
}
}
it throws the compiler error:
The type or namespace name 'ns_1_1' could not be found (are you
missing a using directive or an assembly reference?)
I assume because ns_1_1 is treated like a class which contains another class Foo instead of a namespace, is this correct?
I haven't found the language specification, where is this documented? Why is the compiler not smart enough to check if there's a class or namespace(-part)?
Here's another - less abstract - example of what i mean:
using System.Data;
public class Program
{
public Program()
{
using (var con = new SqlClient.SqlConnection("...")) // doesn't work
{
//...
}
}
}
Edit: now i know why this seems very strange to me. It works without a problem in VB.NET:
Imports System.Data
Public Class Program
Public Sub New()
Using con = New SqlClient.SqlConnection("...") ' no problem
End Using
End Sub
End Class
This obvious way unfortunately not working but you can make all this by an alias namespace:
using ns_1_1 = ns_1.ns_1_1;
public class Program
{
public Program()
{
var no_foo = new ns_1_1.Foo();
}
}
The documentation says:
Create a using directive to use the types in a namespace without having to specify the namespace. A using directive does not give you access to any namespaces that are nested in the namespace you specify.
So the using only includes the types (not the namespaces) that are defined in the specified namespace. In order to access types of nested namespace you need to specify it explicitly with a using directive as you did in your first example.
This is documented in the standard in 3.8 Namespace and Type Names, but it's a bit convoluted to follow.
The gist of it that a partial namespace reference is only looked for in the namespace where it occurs, and each layer outwards. using-directives are not checked.
In your example, ns_1_1.Foo would be found if Foo is found anywhere in:
Program.Program.ns_1_1.Foo
Program.ns_1_1.Foo
ns_1_1.Foo
Partial namespaces will work only if your current class is part of that partial namespace. Using statements are not considered for accessing types through partial namespace.
For instance this will work because your current namespace is ns_1
namespace ns_1
{
public class Program
{
public Program()
{
var no_foo = new ns_1_1.Foo();
}
}
}
If I have this class declaration
namespace DatabaseCache
{
public class DatabaseCache
{
public static bool somePublicFlag ;
}
}
In another class I have this statement
using DatabaseCache;
Why do i need to write a statement like this in that class
DatabaseCache.DatabaseCache.somePublicFlag = true ;
instead of just
DatabaseCache.somePublicFlag = true ;
You don't need that if you don't have a Namespace and Type name collision. A well designed library will not have such collision, So design your library accordingly to avoid such collision.
namespace DatabaseCache
{
//change the name of the class
public class DifferentNameThanNamespace
{
public static bool somePublicFlag ;
}
}
Because the compiler doesn't know if DatabaseCache is referring to the namespace or the class. Even thought you're using the namespace it's still perfectly legal to preface types within that namespace by the namespace, so the call is ambiguous.
You could alias the type by using:
using DC = DatabaseCache.DatabaseCache;
and then just calling
DC.somePublicFlag
but that's just masking the problem - renaming the namespace is a better solution.
In order to avoid ambiguities, it is not recommanded to declare a class with the same same as its namespace.
The Framework Design Guidelines say in section 3.4 “do not use the same name for a namespace.
To learn about how to activate/disable this kind of warning see this link
(Of course the advice is to not use the same name for two distinct things.)
Answer with an extension. Suppose you have one file with:
namespace DatabaseCache
{
public class DatabaseCache // same name as namespace :-(
{
public static bool somePublicFlag;
}
public class somePublicFlag // evil other type
{
}
}
Then now it depends on where you put your using directives relative to your namespace. For example, in another file, this will be legal:
namespace Other
{
using DatabaseCache;
class DbcTestClass1
{
void M()
{
DatabaseCache.somePublicFlag = true; // legal!
}
}
}
In the above example, somePublicFlag refers to the field of the class!
However, this is legal as well:
using DatabaseCache;
namespace Other
{
class DbcTestClass2
{
void M()
{
var instance = new DatabaseCache.somePublicFlag(); // legal!
}
}
}
With that placing of the using directive, the somePublicFlag refers to the "evil" class of that name. The qualifier DatabaseCache. in this case is redundant, but it is still seen as a reference to the namespace global::DatabaseCache because the global namespace (null namespace) is searched first in this case.
To learn more, see my answer elsewhere. It all depends on the order in which the different namespaces (including the global namespace) are searched for a matching name.
I have a structure with several namespaces, and in each namespace I have one static class that is sort of a small, little spider in the net of that namespace. Like the head of the department.
Let's take an example of two namespaces, Foo.Bar.Baz and Foo.Bar.Quux.
I have one file which looks like this:
namespace Foo.Bar.Baz
{
static class Baz
{
public static void DoSomething()
{
Console.Writeline("Doing something...");
}
}
}
And then a second file:
using Foo.Bar.Baz
namespace Foo.Bar.Quux
{
static class Quux
{
public static void GetToWork()
{
Baz.DoSomething();
}
}
}
Now, I get an error in the second file when I try to compile because it thinks that Baz is the namespace and not the class. But since I have the line using Foo.Bar.Baz it should be fine to use any class inside that namespace without needing to prefix it with the name of the namespace, right? I can use other stuff from that namespace correctly, but not a class with the same name.
It kinda feels like the compiler secretly adds this line to every file: using Foo.Bar.
Also, I cannot just put the static Baz class inside the Foo.Bar namespace since then I will get errors saying that Foo.Bar.Baz is not a namespace (since I have other stuff in that namespace and have files that use that namespace). Then it seems the compiler sees the static class and decides that Foo.Bar.Baz is a static class and not a namespace.
Of course, I could just rename the static classes to something like Manager but then I would still have to spell out the full Baz.Manager.SomeMethod and Quux.Manager.SomeMethod in files that need to access stuff from both namespaces. This feels rather clumpsy, I'd rather just have it be Baz.SomeMethod and Quuz.SomeMethod.
Any ideas?
Maybe this can help:
using Baz = Foo.Bar.Baz.Baz;
Since Baz is a static class, it cannot contain instance members. So, DoSomething() must be declared as a static method.
Once you have this, you can either do this:
using Foo.Bar.Baz;
public void GetToWork()
{
Baz.Baz.DoSomething();
}
or this:
using baz = Foo.Bar.Baz.Baz;
public void GetToWork()
{
baz.DoSomething();
}
However, I do agree with the comments in your question that using the same name for the namespace (logical container for a set of classes) and its containing class (encapsulates data and behavior) may result in readability / maintainability issues.
How is it possible that .NET is finding the wrong 'MyType' in this scenario?
I have a type A.B.C.D.MyType in a project that I'm working on, and I'm referencing a DLL that has a type A.B.MyType? I do not have any 'using A.B;' statements anywhere in my code, and I do have 'using A.B.C.D;'. When I compile, the compiler thinks any naked reference to 'MyType' means 'A.B.MyType'.
I know I could just rename the class or use an alias, but I'm wondering how this is even possible.
Any ideas?
Thanks!
Are you working in a namespace that is under A.B namespace? (for example A.B.X) if so the C# namespace resolutions (ECMA-334 C# Language Specification : 10.8 10.8 Namespace and type names) says:
... for each namespace N, starting
with the namespace in which the
namespace-or-typename occurs,
continuing with each enclosing
namespace (if any), and ending with
the global namespace, the following
steps are evaluated until an entity is
located...
and then followed by:
If K is zero and the namespace
declaration contains an
extern-alias-directive or
using-aliasdirective that associates
the name I with an imported namespace
or type, then the
namespace-or-type-name refers to that
namespace or type
This means that name resolution starts at the current namespace and searches all namespaces up to the root, and only after this hierarchical search ends, then the namespaces imported with the using clause are searched.
The following example prints "Ns1.Foo"
using Ns1.Foo.Foo2;
namespace Ns1.Foo
{
class Foo
{
public void Print()
{
System.Console.WriteLine("Ns1.Foo");
}
}
}
namespace Ns1.Foo.Foo2
{
class Foo
{
public void Print()
{
System.Console.WriteLine("Ns1.Foo.Foo2");
}
}
}
namespace Ns1.Foo.Bar
{
class Bar
{
public void Print()
{
new Foo().Print();
}
static void Main()
{
new Bar().Print();
}
}
}
Edit: Adding a using clause inside a namespace, will make so that the namespace is searched before the hierarchical search of current namespace is done is done. Change the example to:
namespace Ns1.Foo.Bar
{
using Ns1.Foo.Foo2;
class Bar
{
public void Print()
{
new Foo().Print();
}
static void Main()
{
new Bar().Print();
}
}
}
and Ns1.Foo.Foo2 will be printed.
Edit: changed example
Is your code in namespace A.B or A.B.C? If so, that's probably the issue. Use a using directive like this:
using TheTypeIWant = A.B.C.D.MyType;
then just refer to TheTypeIWant in your code.
EDIT: I've just tried the "using MyType=A.B.C.D.MyType" option, but that doesn't work. The above is fine though.
Just a guess: in your project properties, is the "default namespace" set to A.B ?