简体   繁体   中英

C# Static Classes & Scope

I am just wondering why can't I define a static class as protected, private etc?

protected static class Class1 {}

The compiler gives the following error message:

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

Non-nested classes in C# can be public or internal but not protected . protected is a member access modifier and does not apply to types defined at the namespace level.

Because it doesn't make sense to have a private or protected member in a namespace. A namespace is not an isolated unity like a class so that a private member makes sense. A namespace can't be inherited, so there is no use for protected members.

You can have a private or proteted static class inside another class:

public class X {

  private static class Y { }

  protected static class Z { }

}

I am just citing the appropriate clause from C# specification:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM