I tried to make a class as private and got this Error "Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal"
I got its meaning but I want to ask why this is not allowed? Are all access modifires not applicable on Class? Why I can't make a class private, protected or protected internal?
Elements defined in a namespace cannot be explicitly declared as private, protected, protected internal or private protected.
Class members, including nested classes and structs, can be public , protected internal , protected , internal , private protected , or private . Class and struct members, including nested classes and structs, have private access by default. Private nested types aren't accessible from outside the containing type.
Because private means that the member is only visible in the containing class. Since a top-level class has no class containing it it cannot be private (or protected). (Internal or public are valid modifiers though).
What would you want private to mean on a top-level class?
Of course all modifiers apply to nested classes, i.e. a class defined within another class.
You can use only public
or internal
in the Namespace level
As Abatonime said, you can only use public
or internal
in the Namespace level.private
, protected
, or protected internal
can only be used in the Class level.
This works
namespace X
{
class A
{
// class code here
private class B // this class is an inner class
{
// class code here
}
}
}
This won't
namespace X
{
class A
{
// class code here
}
private class B // this is a class inside a namespace
{
// class code here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With