Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
Static, in C#, is a keyword that can be used to declare a member of a type so that it is specific to that type. The static modifier can be used with a class, field, method, property, operator, event or constructor.
A static member of a class can be used to keep track of the instances created and maintain common data to be shared among all instances. It can be used in helper and utility classes, which usually contain generic methods that contain abstractions of pure logic. A static constructor is used to make entries in log files, as well as in wrapper class to load the dynamic link libraries (DLLs) required to execute unmanaged code.
In general, a static modifier can be used with data and functions that do not require an instance of a class to be accessed. It is mostly used when the data and behavior of a class do not depend on object identity. The use of static classes and members improves code efficiency.
A static member can only be referenced through the type name and not through an instance of the type. Static cannot be used with a destructor, indexer or any type other than class.
Unlike an instance field, which has a separate copy for each instance of a class, a static field (or variable) is shared by all instances of a class. A static method can be overloaded but not overridden. It cannot access non-static members. Because a static method is not called with a reference to an instance, it is faster to invoke a static method on the call stack than an instance method.
A static class can only include static members. It cannot be instantiated at run time and cannot be inherited. It has its lifetime as that of the application in which it resides. A static constructor does not have parameters and access modifiers. It is invoked automatically before the creation of the first instance or the reference to any static member.
For example, a static class, TemperatureConverter, can be used to convert temperature from Celsius to Fahrenheit and vice versa by providing two methods that contain the code for conversion.
The use of a static modifier has its own limitations that include lack of thread safety, encapsulation and maintainability.