Jiew Meng
Jiew Meng

Reputation: 88197

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

Upvotes: 0

Views: 388

Answers (3)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262939

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.

Upvotes: 1

Paul Michalik
Paul Michalik

Reputation: 4381

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

Upvotes: 0

Guffa
Guffa

Reputation: 700302

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 { }

}

Upvotes: 1

Related Questions