Question

According to object oriented principles, we can define any class in any namespace as private or protected but when I create a class as private or protected I get the following compilation error:

Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal

namespace test
{
    public class A
    {
        public A()
        {
        }
    }

    protected  class B //throwing error
    {
    }
}

I searched for a solution and I found the following on Stack Overflow:

Anything that is not a member of an enclosing type (class) doesn't make sense at all to be protected.

Why can't I declare B as protected?

I guess I don't understand what protected means. What does it mean?

Was it helpful?

Solution 3

In C# you cannot declare classes as protected, except when they are nested within other classes:

namespace test
{
    public class A
    {
        public A()
        {
        }

        protected  class B // nested class
        {
        }
    } 
}

This makes sense because protected means that it should only be accessible by the enclosing class or a class derived from that enclosing class.

If it is ok if class B can be accessed by all classes in the same assembly but not from outside, you can declare the class as internal:

namespace test
{
    public class A
    {
        public A()
        {
        } 
    } 

    internal class B // accessible within same assembly
    {
    }
}

OTHER TIPS

Only nested classes can be marked as protected.

namespace test
{
    public class A
    {
        public A() { }

        protected class B
        {
            public B() { }
        }
    }  
}

Protected says that the class can only be used inside the class it is specified in or inherited from. Therefore it does not make sense to declare a protected class in a namespace. What would this mean? Protected can only be applied to nested classes therefore.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top