The static
modifier means that the type cannot be instantiated or a member cannot be associated with an instance. But whats the benefit of this restriction on instantiation and under what use case scenario should types/members be declared static ?
But whats the benefit of this restriction on instantiation and under what use case scenario should types/members be declared static ?
For members, when you have state that belongs to the class (or should be shared among all instances of the class) or methods that don't depend on instance-level state.
For types, when you have a bag of methods that aren't dependent on instance-level state (for example, System.Math
) including extension methods.
Types are declared static to define, that no instances of this type can be created (and can only contain static data).
Methods are defined static in a non-static class when they do not reference the internal data of a class. This is sometimes important to know when reading or using code.
Several benefits:
Types should be declared as static when you want the compiler to inhibit the instantiation of instances of the type, and prevent the additional of any non-static (instance based) members. All this does is guarantee that you won't inadvertently add a non-static member later.
Members of a non-static class should be declared as static If and Only If the member does not reference any instance-based state of the object, (directly, or indirectly through another non-static member). They cannot reference any non-static member of the type, but non-static members can reference them.
I go by the following principles.
Declare static if:
Don't declare static if:
So mainly, increase cohesion decrease coupling, otherwise you´re fine using static instances.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.