Skip to content
Advertisement

Difference between namespace in C# and package in Java

What is the difference (in terms of use) between namespaces in C# and packages in Java?

Advertisement

Answer

From: http://www.javacamp.org/javavscsharp/namespace.html


Java

Packages are used to organize files or public types to avoid type conflicts. Package constructs can be mapped to a file system.

system.security.cryptography.AsymmetricAlgorithm aa;

may be replaced:

import system.security.Crypography; 
class xxx { ...
AsymmetricAlgorithm aa;

There is no alias for packages. You have to use import statement or fully-qualified name to mention the specific type.

package n1.n2;
    class A {}
    class B {}

or

package n1.n2;
   class A {}

Another source file:

package n1.n2;
   class B {}

Package cannot be nested. One source file can only have one package statement.

C#

Namespaces are used to organize programs, both as an “internal” organization system for a program, and as an “external” organization system.

System.Security.Cryptography.AsymmetricAlgorithm aa;

may be replaced:

using System.Security.Crypography; 
AsymmetricAlgorithm aa;

Alternatively, one could specify an alias for the the namespace, eg

using myAlias = System.Security.Crypography; 

and then refer to the class with

myAlias.AsymmetricAlgorithm 

namespace N1.N2
{
    class A {}
    class B {}
}

or

namespace N1
{
    namespace N2
    {
        class A {}
        class B {}
    }
}
Advertisement