Tuesday, April 5, 2011

C# internal access modifiers

I want to seal of classes in a namespace. I was looking at the "internal" access modifier, but this only seems to seal of classes in an assembly. Can I seal of classes in a namespace?

Or do I have to move stuff into an seperate assembly? But then I will have the problem of visual studio refusing circular assembly references.

From stackoverflow
  • You can still use the internal keyword and expose the internal classes to another assembly via the InternalsVisibleTo attribute in the AssemblyInfo.cs file.

    Marc Gravell : Except [InternalsVisibleTo] is still at the assembly level, not the namespace level.
    Patrik : That's true. But what I know, there is no way of doing this at a namespace level?
  • It is not possible with C#.

    Namespace-level members can only be either public or internal

    You can however, use nested class in C#

    namespace A {
        public class B {
    
            protected class C { }
        }
    
        public class D {
    
            void E() {
                var F = new A.B();    // ok!
                var G = new A.B.C();  // error!
            }
        }
    }
    
  • No, there is no namespace-specific modifier. One option would be to use inheritance and a "protected" modifier, but having an internal constructor on the base-class so that external code can't subclass it. That might help.

    Rowland Shaw : ...after all if there was a way to restrict to the namespace, people would still be able to define the same namespace in their code and inherit that way...

0 comments:

Post a Comment