VIRA
VIRA

Reputation: 1504

protected internal class working within class but not working outside

I was trying few things and would like to know why this is happening so.

Say, I have a class called A in namespace n and I was trying to create protected internal class B.

namespace n
{
   public class A
   {
      public A()
      {
      }
   }
   protected internal class B //throwing error
   {
   }
}

But when i try like this (B as a sub class of A), its not throwing error and its built success. Could you explain me why it is so?

namespace n
{
   public class A
   {
      public A()
      {
      }
      protected internal class B // its not throwing error
      {
      }
   }      
}

Am i missing anything theoretically? Its quite a bit confusing.

Upvotes: 4

Views: 4561

Answers (3)

Tigran
Tigran

Reputation: 62248

protected declares visiblity level for derived types.

In your first case you declare class inside namespace. There is no any polymophic support for namespaces, so there is no any sence of using protected classes in namespace

In second case, instead, you use it inside other classe (class A), which make it visible for all children of A class.

Upvotes: 1

Habib
Habib

Reputation: 223187

Look at the error.

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

Only internal or public members are allowed outside the class.

Your second case is defining the class B as member of class A that is why you are not getting the error.

You may see Access Modifiers C#

Classes and structs that are declared directly within a namespace (in other words, that are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified.

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174289

A class can't be protected except when it is inside another class.

The protected keyword is only valid for members of a class. In your second example, class B happens to be that member.

Think about it:
protected means: Derived classes can access this member.
As there is no such concept as derived namespaces, the protected keyword doesn't make sense for members of a namespace.

Upvotes: 4

Related Questions