In c#, static is a keyword or a modifier that is useful to make a class or methods or variable properties, not instantiable which means we cannot instantiate the items which we declared with a static
modifier.
The static members which we declared can be accessed directly with a type name. Suppose if we apply a static
modifier to a class property or a method or variable, we can access those static members directly with a class name instead of creating an object of a class to access those properties.
Following is the example of defining a class with static properties, and those can be accessed directly with the type instead of a specific object name.
If you observe the above example, we defined variables with static
keyword, and we can access those variables directly with a type name like User.name or User.location and User.age.
Following is the example of accessing the variables directly with a type name in the c# programming language.
If you observe the above statements, we are accessing our static properties directly using the class name instead of the class instance.
Generally, in c# the instance of a class will contain a separate copy of all instance fields so that the memory consumption will increase automatically, but if we use static
modifier, there is only one copy of each field, so automatically, the memory will be managed efficiently.
In c#, we can use static
modifier with classes, methods, properties, constructors, operators, fields, and events, but it cannot be used with indexers, finalizers, or types other than classes.
Following is the example of creating a class by including both static and non-static variables & methods. Here we can access non-static variables and methods by creating an instance of the class, but it won't allow us to access the static fields with an instance of the class so the static variables and methods can be accessed directly with the class name.
If you observe the above example, we created a class called “User” with static and non-static variables & methods. Here we are accessing non-static variables and methods with an instance of the User class, and static fields & methods are able to access directly with the class name (User).
The following diagram will illustrate more details about how static and non-static variables & methods can be accessed in our c# application.
If you observe the above diagram, it clearly says that non-static fields and methods can be accessed only with an instance of the class, and the static fields & methods can be accessed directly with the class name.
When you run the above c# program, you will get the result below.
This is how you can use static
keyword in our c# applications to make a class or methods or variable properties not instantiable based on our requirements.