Namespace-only class visibility in C#/.NET?

internal is assembly (strictly speaking module) privacy. It has no effect on namespace visibility.

The only way to achieve privacy of a class from other classes within the same assembly is for a class to be an inner class.

At this point if the class is private it is invisible to anything not in that class or the outer class itself.

If protected it is visible to everyone that could see it when private but is also visible to sub classes of the outer class.

public class Outer
{
    private class Hidden     { public Hidden() {} }
    protected class Shady    { public Shady() {} }
    public class Promiscuous { public Promiscuous() {} }
}

public class Sub : Outer
{
    public Sub():base() 
    {
        var h = new Hidden();      // illegal, will not compile
        var s = new Shady();       // legal
        var p = new Promiscuous(); // legal
    }
}

public class Outsider 
{
    public Outsider() 
    {
        var h = new Outer.Hidden();      // illegal, will not compile
        var s = new Outer.Shady()        // illegal, will not compile
        var p = new Outer.Promiscuous(); // legal
    }
}

In essence the only way to achieve what you desire is to use the outer class as a form of namespace and restrict within that class.


I don't think that what you want is possible.


You can make the classes internal but this only prevents anyone outside of the assembly from using the class. But you still have to make a separate assembly for each namespace that you want to do this with. I'm assuming that is why you wouldn't want to do it.

Getting the C# Compiler to Enforce Namespace Visibility

There is an article here (Namespace visibility in C#) that shows a method of using partial classes as a form of "fake namespace" that you might find helpful.

The author points out that this doesn't work perfectly and he discusses the shortcomings. The main problem is that C# designers designed C# not to work this way. This deviates heavily from expected coding practices in C#/.NET, which is one of the .NET Frameworks greatest advantages.

It's a neat trick… now don't do it.

Tags:

C#

.Net