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.
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.
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.
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.
Anything that is not a member of an enclosing type (class) doesn't make sense at all to be protected
. protected members are only for those to access who derives from your defined type that contains the member, and in the first example case you are missing that type definition.
来源:https://stackoverflow.com/questions/12403647/protected-internal-class-working-within-class-but-not-working-outside