Why declare Static for all methods of a Static class?

Asked

Viewed 81 times

2

I was studying here C# until I got to the part about the static. The teacher shows that it is possible to use this statement in methods and even in the class itself.

The problem is that when using the static in the class, all methods shall be declared as static obligatorily. My question is: why should I declare static in all methods if I already declare that the class is static?

Why can’t the compiler simply set the methods to static implicitly when declaring the class to be static, so you don’t need to add this statement to dozens of methods and attributes like in the example below?

static class Class1 {
    static public void Method1(){...}
    static public void Method2(){...}
    static public void Method3(){...}
}

// Bem melhor a forma abaixo não é ?

static class Class2 {
    public void Method1(){...}
    public void Method2(){...}
    public void Method3(){...}
}

1 answer

5


And why should you stop saying that the static method is static?

It’s a matter of taste. You think that typing less is more important, the language creators thought it was more important to be more readable and consistent. If the method is static say it is static, in other classes and interface have to say, say in this too.

The compiler could accept this, no technical reasons prevent, but language has aesthetics and preferred so.

But there are doubts as to which is the best way. One of the C# compiler writers says how hard it is to decide what is best to do Eric Lippert’s response on Soen:

I get questions like that all the time. Basically, the question boils down to "when in fact a stated member can be deduced by the compiler, the explicit statement of that fact must be (1) mandatory, (2) optional or (3) prohibited?"

There is no easy answer. Each one should be taken case by case. It is necessary to place static in a member of a static class. Place new in a hidden rather than a substitute method of a class derivative is optional. It is forbidden to place static in a const.

Considering your scenario briefly, it seems bizarre to make it outlawed. You have a whole class full of methods marked as static. You decide to make the class static and that means you must remove all static modifiers? That would be weird.

It seems bizarre to make it optional; suppose you have a class static and two methods, one marked as static and the other not. Like the Static is usually not the pattern, it seems natural to think that there is a difference between them. Making it optional seems to be potentially confused.

This makes it mandatory, as the least bad of the three options.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.