0

Assume that I have a class in which all members (excluding the indexer) are set to static, should I make the class static?

kiss my armpit
  • 3,413
  • 1
  • 27
  • 50
  • 1
    I know this is closed, but you cannot create an instance of a static class(disregarding reflection), so with the indexer non-static it wouldn't even compile. – Silvermind Sep 17 '14 at 08:40
  • @Silvermind You can use reflection to create instances of an abstract/static class? – CodesInChaos Sep 17 '14 at 08:48
  • Indexers, for some reason, cannot be `static`. You would need to remove the indexer. Is that a `get`/`set` indexer, or is it `get` only? You could replace it with a method (or a pair of methods); methods can be `static` of course. In my opinion it sounds like you should make the class static. – Jeppe Stig Nielsen Sep 17 '14 at 09:07
  • @Silvermind Indexers _must_ be non-static in C#. This is a (peculiar) language design decision. That is not related to the fact that static classes cannot be instantiated. The entire meaning of a static class, of course, is that it cannot have instances, and as CodesInChaos hints, this cannot be circumvented with reflection. See also [this answer](http://stackoverflow.com/a/401381/1336654) and the rest of that thread. – Jeppe Stig Nielsen Sep 17 '14 at 09:12
  • @TimSchmelter Duplicate of that? Even if the question is (too) short, it is still more specific than the general "When should you use static classes?" I see the thread as meaning "Is the presence of an indexer alone a valid reason to _not_ make a class static?" – Jeppe Stig Nielsen Sep 17 '14 at 09:21
  • @JeppeStigNielsen: the indexer must be non-static. With that in mind the proposed duplicate answers this question and even [MSDN](http://msdn.microsoft.com/en-us/library/79b3xss3%28v=vs.80%29.aspx) does(_"A class can be declared static, indicating that it contains **only** static members."_). – Tim Schmelter Sep 17 '14 at 09:30
  • @JeppeStigNielsen I Didn't really tought it through :) and you're right of course. Fact remains, however, that a static class with non-static members wouldn't even compile and the OP could have tried it regardless. Whether the compiler complained about the indexer being static or not, would have at least lead to a more thorough question. – Silvermind Sep 17 '14 at 12:16

0 Answers0