Michael Haddad
Michael Haddad

Reputation: 4455

How to force a namespace member to be visible only to members of its direct containing namespace in C#?

Consider the following code:

using System;

namespace Nesting
{
    class Program
    {
        static void Main()
        {
            new Nested.Class().Method();
        }
    }

    namespace Nested
    {
        internal class Class
        {   
            internal void Method()
            {
                Console.WriteLine("Inside Method");
            }
        }
    }
}

The output:

Inside Method

Which means that Nesting members are allowed to access internal members of Nested. Is there a way to force members of Nested to be visible only to other Nested members?

Upvotes: 0

Views: 116

Answers (2)

Rowland Shaw
Rowland Shaw

Reputation: 38128

In short, Not within the same assembly.

Unlike Java, the internal accessibility (Friend in VB.Net) is to make the class/member only visible within the same assembly.

Strictly speaking the using reflection, you could still get to the hidden bits in another assembly.

An alternate scenario would be to use nested classes (rather than namespaces), so something like:

internal class Nested
{
    protected class Class
    {   
        // Only usable from the Nested class
        internal void Method()
        {
            Console.WriteLine("Inside Method");
        }
    }
}

}

Upvotes: 3

Patrick Hofman
Patrick Hofman

Reputation: 157118

No, you can't. All three relevant access modifiers don't give what you want. There is no way to enforce this without pulling the nested class to another assembly.

Upvotes: 1

Related Questions