Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define "anonymous namespace" in C#?

Tags:

namespaces

c#

In C++, in order to define a symbol that is only accessible within the same file, we say

namespace 
{
    class my_private_class
    { ... }
}

But can I do the same thing in C#? Or do I have to say

namespace __DO_NOT_USE_OUT_OF_.xxx.cs__ 
{       
  public MyPrivateClass 
  { ... }
}

using __DO_NOT_USE_OUT_OF_.xxx.cs__;

(assuming this is in a file called xxx.cs)? The later, of cause, will depend on the other programmer regards it or not.

like image 208
Earth Engine Avatar asked Oct 02 '22 07:10

Earth Engine


2 Answers

There's no anonymous namespaces in C#, but you can exploit static classes:

namespace MyNamespace // <- Just a namespace
{
    // Anonymous Namespace emulation:
    //   static class can't have instances and can't be inherited, 
    //   it's abstract and sealed
    internal static class InternalClass // or public static class
    {
        // private class, it's visible within InternalClass only  
        class my_private_class 
        { ... }
    }
}
like image 83
Dmitry Bychenko Avatar answered Oct 05 '22 10:10

Dmitry Bychenko


There is no such thing in C#, we have something called access modifiers which manage the visibility of types.

The usage is against a class or method, such as:

internal class MyType 
{

}

Or

protected void MyMethod() 
{

}

You will have to pick the one that applies to your scenario, here are the details:

public

The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private

The type or member can be accessed only by code in the same class or struct.

protected

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

internal

The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal

The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

like image 21
shenku Avatar answered Oct 05 '22 11:10

shenku