athos
athos

Reputation: 6425

Static class declaring a protected member

I'm reading the book "C# Language", and hit this note from Vladimir Reshetnikov:

If a static class declares a protected or protected internal member, a compile-time error occurs (CS1057).

May I know why? What's wrong with a static class having a protected member? Static class can have private member so I guess this CS1057 error is not due to accessibility, but maybe it's due to come compilation issue? as protected member could be overridden in child classes... but I couldn't figure out why.

Upvotes: 14

Views: 6494

Answers (3)

Rahul
Rahul

Reputation: 77936

Protected members means they can be accessed from child/derived classes. But the main features of static class are:

  1. Only contain static members;

  2. Can't be instantiated;

  3. Are sealed.

That's why static classes can't have protected members.

Upvotes: 3

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

Because you can't inherit a static class, protected serves no purpose - only public and private make sense here.

More details can be found here: Why can't I inherit static classes?

Upvotes: 18

wpppppp
wpppppp

Reputation: 17

Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...

Static methods are only held once in memory. There is no virtual table etc. that is created for them.

If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?

(littleguru)

Upvotes: 0

Related Questions