C# static Keyword
In C#, the static
keyword is used to define a member or type that belongs to the class itself, rather than to a specific instance of the class. When you declare a member or type as static
, it is associated with the type itself, rather than with any particular instance of the type.
Here are some examples of using the static
keyword in C#:
- Static fields:
public class MyClass { public static int myStaticField = 5; }
In this example, the myStaticField
is a static field that belongs to the MyClass
class. This field is associated with the class itself, rather than with any particular instance of the class. You can access the static field using the class name, like this:
int x = MyClass.myStaticField;
- Static methods:
public class MyClass { public static void MyStaticMethod() { // Do something } }
In this example, the MyStaticMethod
is a static method that belongs to the MyClass
class. You can call the static method using the class name, like this:
MyClass.MyStaticMethod();
- Static classes:
public static class MyStaticClass { public static void MyStaticMethod() { // Do something } }
In this example, the MyStaticClass
is a static class. All members of a static class must be static, and you cannot create an instance of a static class. You can call the static method of a static class using the class name, like this:
MyStaticClass.MyStaticMethod();
The static
keyword is useful when you want to define members or types that are shared among all instances of a class, or when you want to define utility classes that do not require an instance to be created. Static members and types are loaded into memory once, when the class is first used, and they remain in memory until the program terminates. This can help improve performance and reduce memory usage, especially when dealing with large or complex classes.