Why do members of a static class need to be declared as static? Why isn't it just implicit?

Obviously there can't be an instance member on a static class, since that class could never be instantiated. Why do we need to declare members as static?


Solution 1:

I get asked questions like this all the time. Basically the question boils down to "when a fact about a declared member can be deduced by the compiler should the explicit declaration of that fact be (1) required, (2) optional, or (3) forbidden?"

There's no one easy answer. Each one has to be taken on a case-by-case basis. Putting "static" on a member of a static class is required. Putting "new" on a hiding, non-overriding method of a derived class is optional. Putting "static" on a const is forbidden.

Briefly considering your scenario, it seems bizarre to make it forbidden. You have a whole class full of methods marked "static". You decide to make the class static and that means you have to remove all the static modifiers? That's weird.

It seems bizarre to make it optional; suppose you have a static class and two methods, one marked static, one not. Since static is not normally the default, it seems natural to think that there is intended to be a difference between them. Making it optional seems to be potentially confusing.

That leaves making it required, as the least bad of the three options.

See http://blogs.msdn.com/b/ericlippert/archive/2010/06/10/don-t-repeat-yourself-consts-are-already-static.aspx for more thoughts on these sorts of problems.

Solution 2:

Because by definition, all of their members must be static. They decided not to give some confusing syntactic sugar.

Solution 3:

It could be implicit, but also it would complicate code reading and lead to confusions.

Solution 4:

Richard,

Hmmmm... I'd guess that the language designers decided that it would be better to be very, very explicit... to avert any possible confusion when a maintainer, who doesn't know the code, jumps into the middle of a static class, and presumes that they are in a "normal" instance context.

But of course, that's just a guess. Most IDE's help you out there anyway, by adding the static modifier "automagically"... or at least highlighting your mistake at "write time", as apposed to "compile time".

It's a good question... unfortunately not one with a "correct" answer... unless someone can turn up a link from a C#-language-designers blog (or similar) discussing this decision. What I can tell you is: "I'd bet $1,000 that it's no accident."

Cheers. Keith.