What does the keyword static mean | C#

In .NET, the keyword "static" is used to define elements (variables, methods, properties) that belong to the type itself rather than to an instance of the type. When a member is declared as static, it means that the member is associated with the type itself, and not with any specific object instance of that type.

Characteristics and behaviors

Here are the key characteristics and behaviors of static members in .NET:

  1. Shared Across Instances: Static members are shared among all instances of a class. This means that all instances of the class have access to and share the same static member.
  2. Accessed Through the Type: Static members are accessed through the type itself, rather than through an instance of the type. They can be accessed using the class name followed by the member name, without needing to create an instance of the class.
  3. Lifetime: Static members exist for the entire lifetime of the application or until they are explicitly destroyed.
  4. Memory Allocation: Static members are allocated memory only once, regardless of the number of instances created.
  5. Global State: Static members can be used to maintain global state or data that needs to be shared across different parts of an application.

Static Variables

class MyClass { public static int myStaticVariable; } // Accessing the static variable MyClass.myStaticVariable = 10;

Static Methods

class Calculator { public static int Add(int a, int b) { return a + b; } } // Calling the static method int result = Calculator.Add(5, 3);

Static Properties

class Circle { private static double _pi = 3.14; public static double Pi { get { return _pi; } set { _pi = value; } } } // Accessing the static property double piValue = Circle.Pi;

Conclusion

The "static" keyword in .NET indicates that a member belongs to the type itself rather than to an instance. It allows for shared access and behavior across all instances of a class and can be accessed without creating an instance of the class.