Junior — Middle
Can you explain the purpose and use of the keyword static in programming language?
sobes.tech AI
Answer from AI
In C#, the keyword static is used to declare class members (fields, methods, properties) that belong to the class itself rather than to any specific instance. This means such members exist in a single copy for the entire class and can be accessed without creating an object.
Application of static:
- Static fields store common data for all objects of the class.
- Static methods can be called directly via the class name.
- Static class — a class that contains only static members and cannot be instantiated.
Example:
public class Calculator
{
public static int Counter = 0; // Shared among all objects
public static int Add(int a, int b)
{
Counter++;
return a + b;
}
}
// Usage:
int result = Calculator.Add(3, 4);
Console.WriteLine(Calculator.Counter); // 1
Thus, static allows creating members shared among all instances and using methods without creating an object.