C# Static
In C#, the static
keyword is used to declare members (fields, methods, properties) that belong to the type itself rather than to a specific instance of the type. This guide explores the usage, syntax, and implications of using static
in C#.
Syntax
public class MyClass
{
public static int myStaticField;
public static void MyStaticMethod()
{
// Static method implementation
}
}
Example
public class Calculator
{
public static int Add(int a, int b)
{
return a + b;
}
}
class Program
{
static void Main()
{
int result = Calculator.Add(5, 10);
Console.WriteLine("Sum: " + result);
}
}
Output
The output will be the sum of the numbers computed by the Add
method.
Explanation
static
members belong to the class itself and can be accessed using the class name.- Static members are associated with the type and not with specific instances of the type.
- In the example, the
Add
method of theCalculator
class is accessed without creating an instance of theCalculator
class.
Use
Use static
in C# when:
- You want to create members that are shared among all instances of a class.
- You need utility methods or properties that don’t rely on instance-specific data.
- Memory efficiency is a concern, as static members are stored in memory once per type.
Important Points
- Static members can be accessed using the class name without creating an instance.
- Static members are initialized once when the type is loaded.
- Static members cannot access non-static (instance) members directly.
Summary
The static
keyword in C# allows for the creation of members that belong to the type itself rather than to specific instances of the type. It facilitates the creation of utility methods, fields, or properties that are shared among all instances of the class. Understanding when and how to use static
members can enhance code modularity, performance, and clarity in C# applications.