Static classes and classes with static methods

Asked

Viewed 599 times

6

When I declare a class static, I am obliged to write my static methods and this class can never be instantiated. Now, I have a common class and I create my methods within it all static. Well, I do consider this class static, out of consideration only for its methods, but is it still a normal class or not? When I speak normal, I mean no static.

2 answers

6


Without the explicit class statement as static she is a normal class and can be instantiated unless you prevent (see how in this question). So it has different implications having the modifier static in addition to documentation that can only have static members.

But one has to ask why create a normal class when all its members are static. Is there a reason? If you don’t find it, you’re doing something "wrong".

Remember that all members need to be static and not just methods.

In C# 6 it is possible to import static classes, normal classes not, with:

using static System.Console;
using static System.Math;

lets use:

WriteLine(Sin(12));

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

If these classes were not static, you could not do this. Just to quote an example.

  • 2

    The reason for the post was just understand the theory of the thing. As for creating a class with Static methods and an unusual class, of course this should not happen. This question of mine was motivated by the post of Private Builder. Only to understand. Sometimes in a job interview guys often ask things to know the level of theoretical understanding that the candidate possesses and understand is always good. I have done a lot of things without understanding what is being done and that is bad. Today I solved a situation of logic for the colleague by the simple understanding of the thing. That’s very good.

  • @pnet understood and realized the intention. Look, it may even have reason, see the example in my answer on link I passed the answer), there everything is static, can not instantiate the class (because the constructor is private) and the class is not static. It’s rare to need, but there is a case.

  • 1

    Okay, I registered at Area 51 and is giving out Unregistered user. I don’t understand.

2

It remains a non-static class because you can instantiate it.

Static methods are identical in all instances of class objects.

Static attributes are identical in all instances of class objects, such as methods. A common use of static attributes is the counting of objects in that class.

  • A static method has no direct access to nonstatic variables of an instance of its class.

  • It makes sense. Edited.

Browser other questions tagged

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