13

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.

Cristian Ciupitu
  • 20,270
  • 7
  • 50
  • 76
athos
  • 6,120
  • 5
  • 51
  • 95

3 Answers3

18

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?

Community
  • 1
  • 1
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
  • 4
    It is implied, but I think it would be worth stating explicitly in your answer that `private` members are ok. – tehDorf Sep 24 '12 at 20:12
  • @tehDorf it's mentioned in the question itself: "Static class can have private member" - sorry but can't see the point in adding this into the answer. – Shadow The GPT Wizard Sep 25 '12 at 07:27
  • 1
    @ShadowWizard Ah, sorry, I missed that. I got linked here by Google not knowing that private members were allowed and I didn't read his post all the way. Thanks for your answer. – tehDorf Sep 26 '12 at 16:50
3

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.

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
Rahul
  • 76,197
  • 13
  • 71
  • 125
0

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)

wpppppp
  • 17
  • 6